【发布时间】:2019-02-28 13:11:09
【问题描述】:
我的问题是关于使用 max 函数在字典中查找最大值。
我创建了一个如下所示的字典:
cc_GDP = {'af': 1243738953, 'as': 343435646, etc}
我希望能够简单地找到并打印每个国家/地区的最高 GDP 值。
阅读类似问题后,我的最佳尝试如下(我目前正在阅读 Python 速成课程书,其中已获取此代码的基础,请注意 get_country_code 函数只是为国家/地区提供 2 个字母缩写在 GDP_data json 文件中):
#Load the data into a list
filename = 'gdp_data.json'
with open(filename) as f:
gdp_data = json.load(f)
cc_GDP` = {}
for gdp_dict in gdp_data:
if gdp_dict['Year'] == 2016:
country_name = gdp_dict['Country Name']
GDP_total = int(gdp_dict['Value'])
code = get_country_code(country_name)
if code:
cc_GDP[code] = int(GDP_total)
print(max(cc_GDP, key=lambda key: cc_GDP[key][1]))
这提供了以下错误'TypeError: 'int' object is not subscriptable'
请注意,如果在打印函数中省略 [1],这确实提供了与最高值相关的最高键,但不会返回我希望实现的最高值本身。
任何帮助将不胜感激。
【问题讨论】: