Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all the keys with the same highest value?

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.

like image 786
Shoryu Avatar asked Sep 10 '14 09:09

Shoryu


People also ask

How do you get all the keys with the highest value in a dictionary?

To find the key with maximum value in a Python dictionary d , call max(d, key=d. get) . This returns the key with maximum value after applying the dict. get(k) method to all keys k to get their associated values.

Can multiple keys have the same value?

You can't have two keys with the same value. That each key should be unique is easy to understand.

How do I return a key to the highest value in Python?

The simplest way to get the max value of a Python dictionary is to use the max() function. The function allows us to get the maximum value of any iterable.

How do we find highest 2 values in a dictionary?

We can find the second largest value in a dictionary by sorting the values of the dictionaries and then retrieving the second last element from the sorted list.


3 Answers

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.

like image 61
xoryouyou Avatar answered Oct 31 '22 15:10

xoryouyou


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).

like image 45
Taohidul Islam Avatar answered Oct 31 '22 15:10

Taohidul Islam


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)
like image 31
monkut Avatar answered Oct 31 '22 15:10

monkut