Gonzalo Gonzalo - 11 months ago 64
Python Question

Collections Counter module issue with most_common class

I have a dictionary made from a List called ltst3_upper, and now I am trying to use the class most_common to get only the top 10 key:values with the below code:

result3 = Counter(list3_upper).most_common(10)
sort_result3 = OrderedDict(sorted(result3.items(), key=operator.itemgetter(1), reverse=True))

I am lopping this code in several Lists which are 'organized' with Counter, and some of them have more than 10 keys:values, so I want to trim the Dict.

Ps. as you can see besides the top 10 values I am also ordering the from highest to smallest, but i dont think the problem is there.

The error is:

AttributeError: 'list' object has no attribute 'items'

Is this happening because some Lists do not have 10 keys:values?

Thanks a lot for any input you might have.

Answer Source

As the documentation states,most_common returns a list of the most common elements. .items is a dict method - lists don't have items. If you want to do something to all members in the list, you'd iterate over them..:

for result in result3:
    o = OrderedDict(sorted(result.items(), key=operator.itemgetter(1), reverse=True))

but this won't work either - the individual members of the list are tuple, not dict - and tuple objects don't have an items method. Instead, just create the OrderedDict with result:

from collections import Counter, OrderedDict
import operator

list3_upper = ['a', 'e', 'a']

result3  = Counter(list3_upper).most_common(10)

result_dict = OrderedDict(result3, key=operator.itemgetter(1), reverse=True)
>>> OrderedDict([('a', 2), ('e', 1)])