7

Let's consider sample dictionaries of (key, value) pairs as follows:

 dict1 = {'a' : 10, 'x' : 44, 'f': 34, 'h':89, 'j': 90, 'd': 28, 'g' : 90}
 dict2 = {'a' : 10, 'x' : 44, 'f': 34, 'h':89, 'j': 90, 'd': 28}

Of all the values in the dictionaries, 90 is the highest. I need to retrieve the key or keys that correspond to it.

What are the possible ways to get this done? Which is the most efficient one, and why?

Note:

  1. Keys and/or values are not in order for the dictionary. The program keeps adding new (key, value) pairs to the dictionary.

  2. There might be more than one key for max(value)

    a) If a dict has only one key corresponding to max(value), then the result should be just a string (i.e. Key). Example: dict2 above should return 'j'

    b) If a dict has more than one key corresponding to max(value), then the result should be list of strings (i.e. keys). Example: dict1 above should return ['j', 'g']

aschultz
  • 1,658
  • 3
  • 20
  • 30
Kumar
  • 314
  • 3
  • 5
  • 16
  • Returning either a string or a list of strings seems likely to result in unnecessary branching later. 90% of the time you're better off always returning a list. – DSM May 15 '13 at 16:10

2 Answers2

8

Use max() and list comprehension:

>>> dic = {'a' : 10, 'x' : 44, 'f': 34, 'h':89, 'j': 90, 'd': 28,"k":90}
>>> maxx = max(dic.values())             #finds the max value
>>> keys = [x for x,y in dic.items() if y ==maxx]  #list of all 
                                                   #keys whose value is equal to maxx
>>> keys
['k', 'j']

Create a function:

>>> def solve(dic):
    maxx = max(dic.values())
    keys = [x for x,y in dic.items() if y ==maxx] 
    return keys[0] if len(keys)==1 else keys
... 
>>> solve({'a' : 10, 'x' : 44, 'f': 34, 'h':89, 'j': 90, 'd': 28})
'j'
>>> solve({'a' : 10, 'x' : 44, 'f': 34, 'h':89, 'j': 90, 'd': 28, 'g' : 90})
['g', 'j']
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
7

You can do:

maxval = max(dict.iteritems(), key=operator.itemgetter(1))[1]
keys = [k for k,v in dict.items() if v==maxval]
karthikr
  • 97,368
  • 26
  • 197
  • 188
  • It does not work if the dict has more than one key for the corresponding max(val). See the updated dict1 and dict2 definitions above for more details. – Kumar May 15 '13 at 16:03
  • Your new code won't work, because `maxval` isn't the maximum value, but one of the keys that hits the maximum value. – DSM May 15 '13 at 16:12