[英]Python: Combine 2 list of dictionaries
I have this 2 list of dictionaries我有这两个字典列表
a = [{'Month': 'Sep 2021', 'Like': 6}, {'Month': 'Oct 2021', 'Like': 7}]
b = [{'Month': 'Aug 2021', 'View': 20}, {'Month': 'Oct 2021', 'View': 8}]
I want this result我想要这个结果
c = [{'Month': 'Aug 2021', 'Like': 0, 'View': 20},
{'Month': 'Sep 2021', 'Like': 6, 'View': 0},
{'Month': 'Oct 2021', 'Like': 7, 'View': 8}]
I tried this one我试过这个
d = defaultdict(dict)
for l in (a, b):
for elem in l:
d[elem['Month']].update(elem)
c = d.values()
but the result is this但结果是这样
dict_values([{'Month': 'Aug 2021', 'View': 20},
{'Month': 'Sept 2021', 'Like': 6},
{'Month': 'Oct 2021', 'Like': 7, 'View': 8}])
How can I add 0 if there is no value?如果没有值,如何添加 0?
Thanks!谢谢!
根据评论中的@kaya3,我通过使用得到结果
d = defaultdict(lambda: {'Like': 0, 'View': 0})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.