簡體   English   中英

獲取字典列表的最大鍵

[英]Get max keys of a list of dictionaries

如果我有:

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}

請改用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})
>>> 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}
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}

這樣的事情應該有效:

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])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM