Skip to content Skip to sidebar Skip to footer

Python Counting Countries In Dictionary

I'm writing a function that counts the number of times a country appears in a dictionary and returns the country that appeared the most. If more then one country appears the most t

Solution 1:

counter = {}
for painting_list in db.values():
    for painting in painting_list:
        country = painting[-1]
        counter[country] = counter.get(country, 0) + 1
maxcount = max(counter.values())
themax = [k for k, count in counter.items() if count == maxcount]

Solution 2:

Flatten the values to get a list of the countries:

>>> [x[-1] for X in d.values() for x in X]
['Spain', 'France', 'Italy']

And a Counter can give you the most frequent ones directly:

>>> from collections import Counter
>>> countries = [x[-1] for X in d.values() for x in X]
>>> Counter(countries).most_common()
[('Italy', 1), ('Spain', 1), ('France', 1)]

Post a Comment for "Python Counting Countries In Dictionary"