0

I have a python dictionary with values and I need to search the maximum key.

data={'A': 1,'C': 3, 'H': 1,'I': 1, 'B': 1,'J': 2,'S': 1, 'D': 3, 'N': 2}

I try max(data, key=data.get).This gives the C as an answer.But I'd like to get C & D as an answer,since both C and D are the highest number.

How this can be done in Python?

Mahbub
  • 11
  • 1
  • 8

3 Answers3

4

You can not do this with max alone, as max will only return a single element. Instead, first, get the maxvalue from data, then filter those keys that have the same value.

>>> data={'A': 1, 'T': 1, 'C': 3, 'H': 1, 'I': 1, 'B': 1, 'O': 1,'J': 2, 'Q': 1, 'S': 1, 'D': 3, 'N': 2}
>>> max_val = max(data.values())
>>> [key for key, val in data.items() if val == max_val]
['C', 'D']
tobias_k
  • 81,265
  • 12
  • 120
  • 179
0

Something like this?

max_keys = [ k for k, val in data.items() if val == max(data.values()) ]
GPhilo
  • 18,519
  • 9
  • 63
  • 89
  • 3
    Here you will evaluate the `max(..)` part **every** time... – Willem Van Onsem Mar 07 '17 at 12:13
  • `values()` already returns a list, and as others said, that way you're calculating `max` every loop. – ChatterOne Mar 07 '17 at 12:14
  • True, it's better to compute the max value separately and then match directly against that. No specific concern for efficiency was noted though, so I preferred the one-liner version. – GPhilo Mar 07 '17 at 12:15
  • @ChatterOne you're right. For some reason I thought in python 3 values() would give an iterator and I wasn't sure whether max would allow for it. I'll update the answer to remove the useless list(). Thanks! – GPhilo Mar 07 '17 at 12:22
0

Create a reverse map.

from collections import defaultdict
reverse_data_map = defaultdict(list)

for k, v in data.items():
    reverse_data_map[v].append(k)  # it becomes a list of keys that share a value

Then get the highest value, and use it to get your keys.

max_keys = reverse_data_map[max(reverse_data_map.keys())]
print max_keys  # ['C', 'D']

As a robust function:

from collections import defaultdict

def get_all_max_keys(d):
    reverse_map = defaultdict(list)
    max_v = 0
    for k, v in d.items():
        max_v = max(max_v, v)  # more efficient method than finding the max afterwards
        reverse_map[v].append(k)
    return reverse_map[max_v]

Calling the function:

data={
    'A': 1, 'T': 1, 'C': 3, 'H': 1,
    'I': 1, 'B': 1, 'O': 1, 'J': 2,
    'Q': 1, 'S': 1, 'D': 3, 'N': 2,
    }

print get_all_max_keys(data)  # ['C', 'D']
Inbar Rose
  • 41,843
  • 24
  • 85
  • 131