4

如果我有:

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

4 回答 4

8

改用collection.Counter()对象,或转换您的字典:

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})
于 2013-06-15T23:39:12.543 回答
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}
于 2013-06-15T23:41:42.533 回答
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}
于 2013-06-15T23:39:16.340 回答
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])
于 2013-06-15T23:44:19.470 回答