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
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())
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With