Python:合并2个字典列表

标签 python

我有这 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/

相关文章:

python - 使用 header 中的 token 登录后 Flask 重定向

python - 使用SciPy的线性代数方法求解三个联立方程

python - 如何在Python中迭代或处理网格或坐标

python - 将列名列表传递给 psycopg2 中的查询

python - 类型错误需要 str 实例,找到 float

python - 如何在 Tkinter 中调整按钮的大小?

python - Python 中等效的 Unix Source 命令

Python Social Auth,扩展断开管道

python - 识别所有有问题的引号实例

python - Google App Engine - 非常慢且昂贵的备份和恢复?