warrior4223 warrior4223 - 19 days ago 9
Python Question

Unable to count countries in a dictionary

I've created 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

countries_appeared_most(dictionary1())

['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 I think is close to the solution but I keep getting a NameError that matches is not defined. Does anyone know what I'm doing wrong? Thanks for any help

Code:

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

Answer

First of all, look at Counter from collections. It already does what you're trying to do.

Secondly, your problem is your indenting. matches is only defined in the scope of your function, but your last line isn't indented, and therefore not considered to be part of the function.

Comments