7

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

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
KingFish
  • 8,773
  • 12
  • 53
  • 81

3 Answers3

15

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())
Community
  • 1
  • 1
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
4

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.

fscore
  • 2,567
  • 7
  • 40
  • 74
  • This does work, but also introduces lots of function calls for key lookups... so all adding unnecessary overhead... – Jon Clements Nov 05 '13 at 01:45
  • @JonClements I agree. You have a better solution as you are using iterations. But this works too. – fscore Nov 05 '13 at 01:47
3

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]
monkut
  • 42,176
  • 24
  • 124
  • 155
  • That's if the object is a `collections.Counter` - and even then, `most_common` isn't really designed for that... It's pretty much like doing `sorted(foo.values(), reverse=True)[0]` – Jon Clements Nov 05 '13 at 01:43