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))
AttributeError: 'list' object has no attribute 'items'
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
dict - and
tuple objects don't have an
items method. Instead, just create the
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) print(result_dict) >>> OrderedDict([('a', 2), ('e', 1)])