17

I want to return the maximum value and its key from a dictionary, and I know that something like the following should do the trick

max(list.iteritems(), key=operator.itemgetter(1))

However in case that the maximum value in a dictionary is 6 and it happens that multiple keys have the same value .. it will always return the first one ! how can I make it return all the keys that has the maximum number as values along with the value. Here is an example of a dictionary with the same maximum value:

dic={0: 1.4984074067880424, 1: 1.0984074067880423, 2: 1.8984074067880425, 3: 2.2984074067880425, 4: 2.2984074067880425}
vaultah
  • 44,105
  • 12
  • 114
  • 143
Ophilia
  • 717
  • 1
  • 10
  • 25

2 Answers2

36

The solution using list comprehension:

dic={0: 1.4984074067880424, 1: 1.0984074067880423, 2: 1.8984074067880425, 3: 2.2984074067880425, 4: 2.2984074067880425}
max_value = max(dic.values())  # maximum value
max_keys = [k for k, v in dic.items() if v == max_value] # getting all keys containing the `maximum`

print(max_value, max_keys)

The output:

2.2984074067880425 [3, 4]
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
12

You can first determine the maximum with:

maximum = max(dic.values())

and then filter based on the maximum value:

result = filter(lambda x:x[1] == maximum,dic.items())

Example in the command line:

$ python2
Python 2.7.12 (default, Nov 19 2016, 06:48:10) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> dic={0: 1.4984074067880424, 1: 1.0984074067880423, 2: 1.8984074067880425, 3: 2.2984074067880425, 4: 2.2984074067880425}
>>> maximum=max(dic.values())
>>> maximum
2.2984074067880425
>>> result = filter(lambda x:x[1] == maximum,dic.items())
>>> result
[(3, 2.2984074067880425), (4, 2.2984074067880425)]

Given you want to present the list of keys are a nice list and the value, you can define a function:

def maximum_keys(dic):
    maximum = max(dic.values())
    keys = filter(lambda x:dic[x] == maximum,dic.keys())
    return keys,maximum

which returns a tuple containing the list of keys and the maximum value:

>>> maximum_keys(dic)
([3, 4], 2.2984074067880425)
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555