Title: Return the maximum value from a dictionary
Tags: python;python-2.7;dictionary;max
Question: 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}

Here is the accepted answer: 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]
Comment for this answer: What if the two values are exactly the same and you dont have a choice of looking by value?
Comment for this answer: That's a tie, any max() algorithm needs to have some sort of tie resolution, maybe lamdba function? @Ahmed

Here is another answer: 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.
&gt;&gt;&gt; dic={0: 1.4984074067880424, 1: 1.0984074067880423, 2: 1.8984074067880425, 3: 2.2984074067880425, 4: 2.2984074067880425}
&gt;&gt;&gt; maximum=max(dic.values())
&gt;&gt;&gt; maximum
2.2984074067880425
&gt;&gt;&gt; result = filter(lambda x:x[1] == maximum,dic.items())
&gt;&gt;&gt; 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:
&gt;&gt;&gt; maximum_keys(dic)
([3, 4], 2.2984074067880425)

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2017:00:02/04/17', 'FavoriteCount': 6.0, 'PostTypeId': 1, 'Tags': '<python><python-2.7><dictionary><max>', 'Title': 'Return the maximum value from a dictionary', 'ViewCount': 116768, 'id': 42044090, 'user_AboutMe': '', 'user_AccountId': 3248463.0, 'user_DisplayName': 'Ophilia', 'user_Reputation': 699.0, 'user_Views': 73.0, 'user_id': 2739381.0}}