15
votes

If I have a dictionary with their corresponding frequency values:

numbers = {'a': 1, 'b': 4, 'c': 1, 'd': 3, 'e': 3}

To find the highest, what I know is:

mode = max(numbers, key=numbers.get)
print mode

and that prints:

b

But if I have:

numbers = {'a': 1, 'b': 0, 'c': 1, 'd': 3, 'e': 3}

and apply the 'max' function above, the output is:

d

What I need is:

d,e

Or something similar, displaying both keys.

4

4 Answers

18
votes
numbers = {'a': 1, 'b': 0, 'c': 1, 'd': 3, 'e': 3}
max_value = max(numbers.values())


[k for k,v in numbers.items() if v == max_value]

prints

 ['e', 'd']

what it does is, loop over all entries via .items and then check if the value is the maximum and if so add the key to a list.

2
votes
numbers = {'a': 1, 'b': 4, 'c': 1, 'd':4 , 'e': 3}
mx_tuple = max(numbers.items(),key = lambda x:x[1]) #max function will return a (key,value) tuple of the maximum value from the dictionary
max_list =[i[0] for i in numbers.items() if i[1]==mx_tuple[1]] #my_tuple[1] indicates maximum dictionary items value

print(max_list)

This code will work in O(n). O(n) in finding maximum value and O(n) in the list comprehension. So overall it will remain O(n).

Note : O(2n) is equivalent to O(n).

1
votes

The collections.Counter object is useful for this as well. It gives you a .most_common() method which will given you the keys and counts of all available values:

from collections import Counter
numbers = Counter({'a': 1, 'b': 0, 'c': 1, 'd': 3, 'e': 3})
values = list(numbers.values())
max_value = max(values)
count = values.count(max_value)
numbers.most_common(n=count)
0
votes

You can use the .items() property and sort after a tuple of count, key - on similar counts the key will decide:

d = ['a','b','c','b','c','d','c','d','e','d','b']

from collections import Counter
get_data = Counter(d)

# sort by count, then key
maxmax = sorted(get_data.items(), key=lambda a: (a[1],a[0]) )
for elem in maxmax:
    if elem[1] == maxmax[0][1]:
        print (elem)

Output:

('a', 1) 
('e', 1)   # the last one is the one with "highest" key

To get the "highest" key, use maxmax[-1].