如何基于 2 个列表创建新的字典列表,并添加具有相同键的两个字典列表的值

问题描述 投票:0回答:1

我有两个字典列表:

list1 = [{"month": "Jan", "amount":1}, {"month": "Feb", "amount":4}]
list2 = [{"month": "Jan", "amount":2}, {"month": "Feb", "amount":4}]

如何创建具有相同键的新字典列表,并添加具有相同“月份”的每个字典的“金额”值?

target = [{"month": "Jan", "amount":3, {"month": "Feb", "amount": 8}]
python list dictionary
1个回答
0
投票

这实现了我上面建议的内容:

from collections import defaultdict

list1 = [{"month": "Jan", "amount":1}, {"month": "Feb", "amount":4}]
list2 = [{"month": "Jan", "amount":2}, {"month": "Feb", "amount":4}]
months = defaultdict(int)
for l in (list1,list2):
    for d in l:
        months[d['month']] += d['amount']

print(months)
target = [{'month':k,'amount':v} for k,v in months.items()]
print(target)

输出:

defaultdict(<class 'int'>, {'Jan': 3, 'Feb': 8})
[{'month': 'Jan', 'amount': 3}, {'month': 'Feb', 'amount': 8}]
© www.soinside.com 2019 - 2024. All rights reserved.