Reputation: 31
The challenge is to return the name of the province that has the largest population. I created a nested dictionary
this_dict = {"Ontario": {"capital": "Toronto", "largest": "Toronto", "population": "14734014"},
"Quebec": {"capital": "Quebec City", "largest": "Montreal", "population": "8574571"},
"Nova Scotia": {"capital": "Halifax", "largest": "Halifax", "population": "979351"},
"New Brunswick": {"capital": "Fredericton", "largest": "Moncton", "population": "781476"},
"Manitoba": {"capital": "Winnipeg", "largest": "Winnipeg", "population": "1379263"},
"British Columbia": {"capital": "Victoria", "largest": "Vancouver", "population": "5147712"},
"Prince Edward Island": {"capital": "Charlottetown", "largest": "Charlottetown", "population": "159625"},
"Saskatchewan": {"capital": "Regina", "largest": "Saskatoon", "population": "1178681"},
"Alberta": {"capital": "Edmonton", "largest": "Calgary", "population": "4421876"},
"Newfoundland and Labrador": {"capital": "St. John's", "largest": "St. John's", "population": "522103"}
}
I created a function and my code so far:
def get_largest_city():
max_population = max([int(i['population']) for i in this_dict.values()])
print(max_population)
This gives me the the number of the province that has the largest number which is 14734014 However, the output I want is for it to return the name of the province instead which in this case should be Ontario.
I'd appreciate any opinions on this, I'm pretty new with Python and just gets confused at times sorry if this isn't explained in the most ideal way and thanks in advance for the help.
Upvotes: 3
Views: 101
Reputation: 59375
You must use the key
argument of the max
built-in:
def get_largest_city():
max_population = max(this_dict.items(), key=lambda item: int(item[1]["population"]))
return max_population[1]["capital"]
Upvotes: 2
Reputation: 2407
>>> max(this_dict, key=lambda k: int(this_dict[k]["population"]))
'Ontario'
Upvotes: 3