Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the Max Value from a Dictionary [duplicate]

I'm sure this is very easy:

say I have the following dictionary:

 foo = { a: 3, b: 10, c: 5 }

What's the most efficient (and cleanest) way to get the value 10

Thanks

like image 752
Paul Avatar asked Nov 05 '13 01:11

Paul


3 Answers

If you're only concerned about finding the max value, and not the key relating to it, then you just access the values of the dict (although the linked post Getting key with maximum value in dictionary? is definitely worth a read)

On Python 2.x:

max(foo.itervalues())

On Python 3.x:

max(foo.values())
like image 122
Jon Clements Avatar answered Nov 14 '22 20:11

Jon Clements


In order to get the max value of the dictionary. You can do this:

>>> d = {'a':5,'b':10,'c':5}
>>> d.get(max(d, key=d.get))
10

Explanation:
max(d, key=d.get) => Gets the key with the maximum value where d is the dictionary
d.get => gets the value associated with that key

Hope this helps.

like image 20
fscore Avatar answered Nov 14 '22 21:11

fscore


Say you have the following Counter object:

from collections import Counter
foo = Counter({ "a": 3, "b": 10, "c": 5 })

You can then use the .most_common() method to get a list of tuples sorted by most to least:

>>> foo.most_common()
[('b', 10), ('c', 5), ('a', 3)]

To get the max just grab the first element:

foo_max = foo.most_common()[0]
like image 23
monkut Avatar answered Nov 14 '22 22:11

monkut