gpt4 book ai didi

python - 将字典列表合并为单个字典,为公共(public)键添加值

转载 作者:行者123 更新时间:2023-12-02 09:58:26 25 4
gpt4 key购买 nike

我怎样才能打开这样的字典列表

dico = [{'a':1}, {'b':2}, {'c':1}, {'d':2}, {'e':2}, {'d':3}, {'g':1}, {'h':4}, {'h':2}, {'f':6}, {'a':2}, {'b':2}]

像这样的一个字典

{'a':3, 'b':4, 'c':1, 'd':5,'e':2,'f':6 , 'g':1 ,'h':6}

此时此刻

result = {}
for d in dico:
result.update(d)
print(result)

结果:

{'a': 2, 'b': 2, 'c': 1, 'd': 3, 'e': 2, 'g': 1, 'h': 2, 'f': 6}

最佳答案

只需将您的字典替换为 collections.Counter它会起作用:

from collections import Counter

dico = [{'a':1}, {'b':2}, {'c':1}, {'d':2}, {'e':2}, {'d':3}, {'g':1}, {'h':4}, {'h':2}, {'f':6}, {'a':2}, {'b':2}]

result = Counter()
for d in dico:
result.update(d)
print(result)

输出:

Counter({'h': 6, 'f': 6, 'd': 5, 'b': 4, 'a': 3, 'e': 2, 'c': 1, 'g': 1})

为什么上述内容适用于 docsCounterupdate :

Elements are counted from an iterable or added-in from another mapping (or counter). Like dict.update() but adds counts instead of replacing them. Also, the iterable is expected to be a sequence of elements, not a sequence of (key, value) pairs.

关于python - 将字典列表合并为单个字典,为公共(public)键添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61363779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com