gpt4 book ai didi

python - 返回嵌套字典中具有最大值的键的名称

转载 作者:行者123 更新时间:2023-12-04 02:30:09 30 4
gpt4 key购买 nike

挑战在于返回人口最多的省份的名称。我创建了一个嵌套字典

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"}

}

到目前为止,我创建了一个函数和我的代码:

 def get_largest_city():
max_population = max([int(i['population']) for i in this_dict.values()])
print(max_population)

这给了我最大数字的省份的数字,即 14734014但是,我想要的输出是返回省名,在本例中应该是安大略省。

如果对此有任何意见,我将不胜感激,我是 Python 的新手,有时会感到困惑,如果没有以最理想的方式解释这一点,我深表歉意,在此先感谢您的帮助。

最佳答案

>>> max(this_dict, key=lambda k: int(this_dict[k]["population"]))
'Ontario'

关于python - 返回嵌套字典中具有最大值的键的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64707071/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com