抓住嵌套字典最高值的2个键 [英] Grab 2 keys with highest values for nested dictionary

查看:125
本文介绍了抓住嵌套字典最高值的2个键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本字典,如下所示:

  bigdict = {

'a' :{'foo':2,'bar':3,'baz':7,'qux':1},
'b':{'foo':6,'bar':4,'baz ':3,'qux':0},
'c':{'foo':4,'bar':5,'baz':1,'qux':6}
}

对于每个字典,我想要抓住具有最高值的2个键,并将导致一个新的字典。



eg

  newbigdict = {
a:{'baz':7,'bar':3},
b :{'foo':6,'bar':4},
c:{'qux':6,'bar':5}
}
/ pre>

任何想法?我已经停留了一段时间。我使用Python 3。

解决方案

这可以使用字典理解看到这篇文章有关 Python Dictionary Comprehension

 >>> def findtoptwo(d):
... toptwo = sorted(d.values())[ - 2:]
... return {k:v for k,v in d.items()如果v in toptwo}
...
>>> newdict = {k:findtoptwo(v)for k,v in bigdict.items()}
>>>> new dict
{'a':{'bar':3,'baz':7},'c':{'qux':6,'bar':5},'b':{'foo' :6,'bar':4}}

这里的逻辑很简单,对于每个键值在字典中,我们检查该值是否存在于前两个值中。为此,我们对字典值进行排序并分割最后两个值。详细了解这里的python片段和内置 已排序这里


I have a dictionary which looks like this:

bigdict = { 

'a': {'foo':2, 'bar':3, 'baz':7, 'qux':1},
'b': {'foo':6, 'bar':4, 'baz':3, 'qux':0},
'c': {'foo':4, 'bar':5, 'baz':1, 'qux':6}
}

And for each dictionary, I want to be able to grab the 2 keys with the highest values and put the results in a new dictionary.

e.g.

newbigdict = {
 a: {'baz':7, 'bar':3},
 b: {'foo': 6, 'bar':4},
 c: {'qux':6, 'bar':5}
}

Any ideas? I've been stuck on this for a while. I use Python 3.

解决方案

This can be solved easily using a dictionary comprehension. See this post for more explanation about a Python Dictionary Comprehension

>>> def findtoptwo(d):
...     toptwo = sorted(d.values())[-2:]
...     return {k:v for k,v in d.items() if v in toptwo}
... 
>>> newdict = {k:findtoptwo(v) for k,v in bigdict.items()}
>>> newdict
{'a': {'bar': 3, 'baz': 7}, 'c': {'qux': 6, 'bar': 5}, 'b': {'foo': 6, 'bar': 4}}

The logic here is simple, For each key-value pair in the dictionary we check if the value is present in the top two values. For this we sort the dictionary values and slice the last two values. Read more about slices in python here and the builtin sorted here.

这篇关于抓住嵌套字典最高值的2个键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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