简体   繁体   English

如何将列表中的字典组合成一个字典,并添加相同键的值?

[英]How to combine dictionaries in a list into one dictionary with values of same keys added?

I am trying to convert a list that contains dictionaries to one dictionary where the values for common keys are added.我正在尝试将包含字典的列表转换为一个字典,其中添加了公共键的值。

Use this list as an example:使用此列表作为示例:

list = [{'Apple': 3, 'Orange': 2}, {'Apple': 1, 'Grapes': 3, 'Orange': 1}, {'Apple': 2}]

I want a function that will take that list as an input and return the following as the output:我想要一个 function ,它将将该列表作为输入并将以下内容作为 output 返回:

{'Apple': 6, 'Orange': 3, 'Grapes': 3}
from collections import Counter

fruit_dicts = [
    {'Apple': 3, 'Orange': 2},
    {'Apple': 1, 'Grapes': 3, 'Orange': 1},
    {'Apple': 2}
]

counter = Counter()
for fruit_dict in fruit_dicts:
    counter.update(fruit_dict)

print(counter)

Output: Output:

Counter({'Apple': 6, 'Orange': 3, 'Grapes': 3})

EDIT Without using collections.Counter :编辑不使用collections.Counter

fruit_dicts = [
    {'Apple': 3, 'Orange': 2},
    {'Apple': 1, 'Grapes': 3, 'Orange': 1},
    {'Apple': 2}
]

counter = {}
for fruit_dict in fruit_dicts:
    for key, value in fruit_dict.items():
        counter.update({key: counter.get(key, 0) + value})

print(counter)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将两个字典与一个字典中的列表值结合在一起,而字典中的列表值链接到另一个字典的键上 - Combine two dictionaries with list values from one dictionary linked to keys of another 如何将字典列表合并为一个字典 - How to combine a list of dictionaries to one dictionary 在字典列表中组合具有相同键的两个相同值 - Combine two same values with same keys in a list of dictionaries 当值相同时如何组合字典的键? - how to combine keys of a dictionary when the values are the same? 如何在 python 中组合(附加值)两个具有相同键的嵌套字典? - How to combine (append values) two nested dictionaries with the same keys in python? 如何将字典列表转换为具有相同键和值总和的字典? - How can I convert a list of dictionaries to a dictionary with same keys and sum of the values? 在Python中将2个具有相同键但值不同的字典组合在一起 - Combine 2 dictionaries with the same keys but different values in Python 当一个字典中的值是其他字典中的键时,如何从多个字典创建新字典? - How to create new dictionary from multiple dictionaries when values from one dictionary are keys in other dictionaries? 将两个具有相同键但不同字典的嵌套字典组合为值 - Combine two nested dictionaries with same keys but different dictionaries as values 如何将具有多个文本列表值的python字典拆分为具有相同值的键的单独字典? - How can I split a python dictionary with multiple text-list values to have separate dictionaries of keys that have the same values?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM