我有这 2 个字典列表
a = [{'Month': 'Sep 2021', 'Like': 6}, {'Month': 'Oct 2021', 'Like': 7}]
b = [{'Month': 'Aug 2021', 'View': 20}, {'Month': 'Oct 2021', 'View': 8}]
我想要这个结果
c = [{'Month': 'Aug 2021', 'Like': 0, 'View': 20},
{'Month': 'Sep 2021', 'Like': 6, 'View': 0},
{'Month': 'Oct 2021', 'Like': 7, 'View': 8}]
我试过这个
d = defaultdict(dict)
for l in (a, b):
for elem in l:
d[elem['Month']].update(elem)
c = d.values()
但结果是这样的
dict_values([{'Month': 'Aug 2021', 'View': 20},
{'Month': 'Sept 2021', 'Like': 6},
{'Month': 'Oct 2021', 'Like': 7, 'View': 8}])
没有值怎么加0?
谢谢!
最佳答案
根据评论中的@kaya3,我通过使用得到结果
d = defaultdict(lambda: {'Like': 0, 'View': 0})
关于Python:合并2个字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69702752/