为嵌套字典抓取具有最高值的2个键

时间:2016-06-04 14:39:58

标签: python 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个键并将结果放入新字典中。

e.g。

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

有什么想法吗?我已经坚持了一段时间。我使用Python 3。

2 个答案:

答案 0 :(得分:1)

使用dictionary comprehension.可以轻松解决此问题。有关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}}

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

答案 1 :(得分:0)

可以使用pandas模块轻松完成:

In [97]: 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},
   ....: }

In [98]: df = pd.DataFrame.from_dict(bigdict)

In [99]: df
Out[99]:
     a  b  c
bar  3  4  5
baz  7  3  1
foo  2  6  4
qux  1  0  6

In [126]: df.apply(lambda x: x.nlargest(2).to_dict()).to_dict()
Out[126]:
{'a': {'bar': 3, 'baz': 7},
 'b': {'bar': 4, 'foo': 6},
 'c': {'bar': 5, 'qux': 6}}

<强>单行:

In [129]: (pd.DataFrame.from_dict(bigdict)
   .....:    .apply(lambda x: x.nlargest(2).to_dict())
   .....:    .to_dict()
   .....: )
Out[129]:
{'a': {'bar': 3, 'baz': 7},
 'b': {'bar': 4, 'foo': 6},
 'c': {'bar': 5, 'qux': 6}}
相关问题