繁体   English   中英

在字典中查找字典中的最高值

[英]Finding the highest value in a dictionary within a dictionary

初学者课程中有一个任务,我们必须在字典中找到某个键​​的最大值。

但是,这些值位于另一个字典中。 所以格式是这样的:

data = {
    'Country1': {2015: 5, 2016: 9, 2017: 2},
    'Country2': {2015: 20, 2016: 10, 2017: 5}
}

当然,那里有两个以上的国家,但基本上我必须找到特定年份(比如 2015 年)的最高值。 任何人都知道如何进行? 我已经查看了几个类似的选项,例如max()lambda但我不确定如何在这种特定情况下使用列表中的列表来使用它们。

你可以这样做:

data = {
    'Country1': {2015: 5, 2016: 9, 2017: 2},
    'Country2': {2015: 20, 2016: 10, 2017: 5}
}

country_with_max_2015 = max(data, key=lambda k: data[k][2015])

在函数max ,lambda 函数将获得值'Country1''Country2' ,它们可用于从data字典中获取'Country1'的值,因此我们可以在 country 的值中找到键2015的值。

您可以使用 for 循环遍历字典字典,我将让您决定如何跟踪找到的最大值。

这是针对python3的,python2看起来会有点不同

data = {'Country1': {2015: 5, 2016: 9, 2017: 2}, 'Country2': {2015: 20, 2016: 10, 2017: 5}}

for country,sub_dict in data.items():
    print(country)
    print(sub_dict)
    
    for year,value in sub_dict.items():
        print(year,value)
data = {'Country1': {2015: 5, 2016: 9, 2017: 2}, 'Country2': {2015: 20, 2016: 10, 2017: 5}}

max_val = 0
for _,inner_dict in data.items():
    max_val = max(inner_dict[2015], max_val)
print(max_val)

以这种方式遍历字典可以最大限度地减少资源使用,尤其是在处理大型数据集时

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM