+2 votes
in Programming Languages by (75.1k points)

I am trying to find 2 keys of a dictionary with maximum values using function most_common(), but the code is giving error.

Here is an example:

>>> aa={'a':10,'b':8,'c':25,'d':15,'e':12}

>>> aa.most_common(2)

AttributeError: 'dict' object has no attribute 'most_common'

1 Answer

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

From the error message, it is clear that you can not use function most_common() with a dictionary. You need to typecast dictionary to Counter and then you can use the function most_common().

Check the following example:

>>> from collections import Counter
>>> aa={'a':10,'b':8,'c':25,'d':15,'e':12}
>>> Counter(aa).most_common()
[('c', 25), ('d', 15), ('e', 12), ('a', 10), ('b', 8)]
>>> Counter(aa).most_common(2)
[('c', 25), ('d', 15)]