[英]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.