warrior4223 warrior4223 - 1 year ago 73
Python Question

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 then it should return a list of the countries.

Example dictionary:

{'Leonardo da Vinci': [("Portrait of Isabella d'Este", 1499, 63.0, 46.0, 'chalk', 'France'), ('The Last
Supper', 1495, 460.0, 880.0, 'tempera', 'Italy')], 'Pablo Picasso': [('Guernica', 1937,
349.0, 776.0, 'oil paint', 'Spain')]}

Since France, Italy, and Spain all only appear once in this dictionary the function should return


['France', 'Italy', 'Spain']

If one of those countries had instead appeared 2 or 3 times the function would return just that country. The current code I have below instead searches for the artist that appears the most but I believe a couple small changes could help me instead return the country that appears the most. Does anyone have advice on how to do this? Thanks for the help


def countries_appeared_most(db):
if not db:
return None
maxcount = max(len(v) for v in db.values())
themax = [k for k, v in db.items() if len(v) == maxcount]
return themax

Answer Source
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]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download