LearningNinja
LearningNinja

Reputation: 447

Finding max value in a dictionary if two or more keys have same values

I have a dictionary say

a = {'2':134,'22':43,'31':134,'29':43}

Now using operator package and max function I could easily find the key with max value. But that returns only one key(That too the last key if the values of keys are same).

max(a.iteritems(),key=operator.itemgetter(1))[0]

How do I return both the keys that has max value.

Upvotes: 0

Views: 2524

Answers (5)

Emisilve86
Emisilve86

Reputation: 354

Another solution could be build an "Inverted-Index List" that is large used in "Machine Learning" and "Web Information Retrieval", so that every time you need to find all keys associated to given value you only have to consult one of the Inverted-Index lists:

inv_ind = {}
for key in a.keys():
    if inv_ind.has_key(a[key]):
        inv_ind[a[key]].append(key)
    else:
        inv_ind[a[key]] = [key]

this solution requires very few line of code, O(n) time, but double space to keep in memory both dictionary. To retrieve the maximum value is sufficient to do:

max(inv_ind.keys())

when you update "a" you also update "inv_ind" so that finding the max can be done immediately using the code above.

Upvotes: 0

Padraic Cunningham
Padraic Cunningham

Reputation: 180481

You could use list comprehension:

a = {'2':134,'22':43,'31':134,'29':43}
m=max(a.values())
print  [k for k in a if a.get(k) == m]
['31', '2']

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1123470

You could sort the items and use itertools.groupby() to find the first group of equal values; the first group is also the maximum:

from itertools import groupby

next([g[0] for g in group]
     for key, group in groupby(
         sorted(a.items(), key=operator.itemgetter(1), reverse=True),
         operator.itemgetter(1)))

This is a O(NlogN) operation.

Demo:

>>> from itertools import groupby
>>> import operator
>>> a = {'2':134,'22':43,'31':134,'29':43}
>>> next([g[0] for g in group]
...      for key, group in groupby(
...          sorted(a.items(), key=operator.itemgetter(1), reverse=True),
...          operator.itemgetter(1)))
['31', '2']

Upvotes: 0

Daniel
Daniel

Reputation: 42768

max_keys = []
max_value = None
for key, value in a.iteritems():
    if max_value is None or value>max_value:
        max_keys = [key]
        max_value = value
    elif value == max_value:
        max_keys.append(key)

Upvotes: 1

Sukrit Kalra
Sukrit Kalra

Reputation: 34513

Make a defaultdict mapping values to keys.

>>> a = {'2':134,'22':43,'31':134,'29':43}
>>> from collections import defaultdict
>>> b = defaultdict(list)
>>> for key, val in a.iteritems():
        b[val].append(key)


>>> b
defaultdict(<type 'list'>, {43: ['29', '22'], 134: ['31', '2']})
>>> max(b)
134
>>> b[max(b)]
['31', '2']

Upvotes: 3

Related Questions