python – Return the maximum value from a dictionary

python – Return the maximum value from a dictionary

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]

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)

python – Return the maximum value from a dictionary

Leave a Reply

Your email address will not be published. Required fields are marked *