Python从嵌套字典中提取最大值 [英] Python extract max value from nested dictionary

查看:112
本文介绍了Python从嵌套字典中提取最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌套的字典,其形式为:

I have a nested dictionary of the form:

 {'2015-01-01': {'time': '8', 'capacity': '5'}, 
  '2015-01-02': {'time': '8', 'capacity': '7'},
  '2015-01-03': {'time': '8', 'capacity': '8'} etc}

使用dictreader从csv文件创建字典.我想做的就是返回容量的最大值.所以在这种情况下是8.

The dictionary is created from a csv file using dictreader. What I would like to be able to do is return the maximum value of capacity. So in this case 8.

我可以使用:

for k,v in input_dict.items():
    if temp_max < int(v['capacity']):
        temp_max = int(v['capacity'])

哪个可行,但我想知道是否有更整洁的方法?我搜索并找到了提取与最大值相关联的顶级密钥的方法,这当然不是我所需要的.见下文:

which works but I wondered if there was a neater method? I've searched and found methods to extract the top level key associated with the maximum value which is of course not what I need. See below:

max(input_dict, key=lambda v: input_dict[v]['capacity'])

它将返回'2015-01-03',所以我想上面的一个衬里有一个简单的mod,可以给我我需要的东西,但是让我很沮丧!

which would return '2015-01-03', So I imagine there is a simple mod to the above one liner that will give me what I need but is has me stumped!

有什么想法吗?

推荐答案

您要

max(int(d['capacity']) for d in input_dict.values())

说明:

如果您不关心键,只需遍历嵌套的字典(即外部字典的值就可以了)

If you don't care about the keys, just iterate over the nested dicts (IOW the outer dict's values)

您的内在命令也将容量"值存储为字符串,我假设您要测试整数值.要找出差异,请检查以下内容:

Also your inner dicts "capacity" values are stored as strings, I assume you want to test the integer value. To find out the difference check this:

>>> max(["1", "5", "18", "01"])
'5'
>>> max([1, 5, 18, 01])
18
>>> 

这篇关于Python从嵌套字典中提取最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆