获取字典列表的最大键

时间:2013-06-15 23:36:58

标签: python list dictionary

如果我有:

dicts = [{'a': 4,'b': 7,'c': 9}, 
         {'a': 2,'b': 1,'c': 10}, 
         {'a': 11,'b': 3,'c': 2}]

如何才能获得最大键,如下所示:

{'a': 11,'c': 10,'b': 7}

4 个答案:

答案 0 :(得分:8)

改为使用collection.Counter() objects或转换字典:

from collections import Counter

result = Counter()
for d in dicts:
    result |= Counter(d)

甚至:

from collections import Counter
from operator import or_

result = reduce(or_, map(Counter, dicts), Counter())

Counter个对象支持通过|操作本机查找每个密钥的最大值; &为您提供最低限度。

演示:

>>> result = Counter()
>>> for d in dicts:
...     result |= Counter(d)
... 
>>> result
Counter({'a': 11, 'c': 10, 'b': 7})

或使用reduce()版本:

>>> reduce(or_, map(Counter, dicts), Counter())
Counter({'a': 11, 'c': 10, 'b': 7})

答案 1 :(得分:5)

>>> dicts = [{'a': 4,'b': 7,'c': 9}, 
...          {'a': 2,'b': 1,'c': 10}, 
...          {'a': 11,'b': 3,'c': 2}]
>>> {letter: max(d[letter] for d in dicts) for letter in dicts[0]}
{'a': 11, 'c': 10, 'b': 7}

答案 2 :(得分:1)

dicts = [{'a': 4,'b': 7,'c': 9}, 
             {'a': 2,'b': 1,'c': 10}, 
             {'a': 11,'b': 3,'c': 2}]

def get_max(dicts):
    res = {}
    for d in dicts:
        for k in d:
            res[k] = max(res.get(k, float('-inf')), d[k])
    return res

>>> get_max(dicts)
{'a': 11, 'c': 10, 'b': 7}

答案 3 :(得分:0)

这样的事情应该有效:

dicts = [{'a': 4,'b': 7,'c': 9}, 
         {'a': 2,'b': 1,'c': 10}, 
         {'a': 11,'b': 3,'c': 2}]

max_keys= {}

for d in dicts:
    for k, v in d.items():
        max_keys.setdefault(k, []).append(v)

for k in max_keys:
    max_keys[k] = max(max_keys[k])