【发布时间】:2021-10-06 12:31:15
【问题描述】:
我有 2 个字典如下:
d1 = {a:2, b:4}
d2 = {a:13, b:3, c:5}
如何将这两者合并,如果一个键为空则加0?
结果应该是
= {a:[2,13], b:[4,3], c:[0,5]}
我试过用这个
d1 = {'a':2, 'b':4}
d2 = {'a':13, 'b':3, 'c':5}
dd = defaultdict(list)
for d in (d1, d2):
for key, value in d.items():
dd[key].append(value)
但我不知道怎么加 0,我真的是编程新手。
【问题讨论】:
-
循环浏览其中一个字典。在另一个字典中找到相应的元素并将它们组合起来。如果找不到,请使用
0。 -
StackOverflow 不是免费的编码服务。你应该try to solve the problem first。请更新您的问题以在minimal reproducible example 中显示您已经尝试过的内容。如需更多信息,请参阅How to Ask,并拨打tour :)
-
将代码添加到问题中,确保其格式正确。
标签: python dictionary merge