抓住嵌套字典最高值的2个键 [英] Grab 2 keys with highest values for nested dictionary
问题描述
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 = {
/ pre>
a:{'baz':7,'bar':3},
b :{'foo':6,'bar':4},
c:{'qux':6,'bar':5}
}
任何想法?我已经停留了一段时间。我使用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屋!