我有一本看起来像这样的字典:
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 个键并将结果放入一个新字典中。
例如
newbigdict = {
a: {'baz':7, 'bar':3},
b: {'foo': 6, 'bar':4},
c: {'qux':6, 'bar':5}
}
有什么想法吗?我已经坚持了一段时间。我使用 Python 3。
请您参考如下方法:
这可以使用 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 .
