+2 votes
in Programming Languages by (75.1k points)
I want to find top two keys of a dictionary that have the largest values.



The output should be: ('c','d')

1 Answer

+1 vote
by (353k points)
selected by
Best answer

You can use most_common() function of Counter module. The function will sort your dictionary in the descending order of the values. You need to pass 2 as an argument to the the function to select top 2 keys. Here is an example:

>>> from collections import Counter
>>> aa={'a':10,'b':8,'c':25,'d':15,'e':12}
>>> keyss = set()
>>> for k,v in Counter(aa).most_common(2):
...     keyss.add(k)
>>> keyss
{'d', 'c'}