Skip to content Skip to sidebar Skip to footer

Getting The Max Value From A Dictionary

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

Solution 1:

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())

Solution 2:

Say you have the following Counter object:

from collections importCounterfoo= 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]

Solution 3:

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.

Post a Comment for "Getting The Max Value From A Dictionary"