如何在Python中将2个字典变成1个?

ayu*_*utu 0 python dictionary list key-value

我有两本词典:

fruit1 = {'apple': 3, 'banana': 1, 'cherry': 1}
fruit2 = {'apple': 42, 'peach': 1}
Run Code Online (Sandbox Code Playgroud)

我想要的最终结果是:

inv3 = {'apple': 45, 'banana': 1, 'cherry': 1, 'peach': 1}
Run Code Online (Sandbox Code Playgroud)

到目前为止,我已经尝试过这个示例代码,因为这个输出看起来几乎与我想要的类似,只是它没有按照我想要的方式打印,而是接近:

d1 = {'apple': 3, 'orange': 1,} 
d2 = {'apple': 42, 'orange': 1}

ds = [d1, d2]
d = {}

for k in d1.keys():
    d[k] = tuple(d[k] for d in ds)
print(ds)
Run Code Online (Sandbox Code Playgroud)

输出将是这样的:

[{'apple': 3, 'orange': 1}, {'apple': 42, 'orange': 1}]
Run Code Online (Sandbox Code Playgroud)

当我尝试使用示例代码输入我的两个词典时:

fruit1 = {'apple': 3, 'banana': 1, 'cherry': 1}
fruit2 = {'apple': 42, 'peach': 1}      

fruit3 = [fruit1, fruit2]
d = {}
            
for k in fruit1.keys():
d[k] = tuple(d[k] for d in fruit3)
print(fruit3)
Run Code Online (Sandbox Code Playgroud)

我收到此错误消息:

Traceback (most recent call last):
  line 8, in <module>
    d[k] = tuple(d[k] for d in ds)
  line 8, in <genexpr>
    d[k] = tuple(d[k] for d in ds)
KeyError: 'banana'
Run Code Online (Sandbox Code Playgroud)

我的问题是:

  1. 如何在不导入任何模块的情况下获得我想要的输出?我只在第 5 章:字典和数据结构自动化无聊的东西
  2. 为什么会出现 KeyError: 'banana' ?

谢谢!

Ctr*_*rlZ 5

有很多方法可以实现这一目标。这是一个:

fruit1 = {'apple': 3, 'banana': 1, 'cherry': 1}
fruit2 = {'apple': 42, 'peach': 1}

inv3 = {}

for d in fruit1, fruit2:
    for k, v in d.items():
        inv3[k] = inv3.get(k, 0) + v

print(inv3)
Run Code Online (Sandbox Code Playgroud)

输出:

{'apple': 45, 'banana': 1, 'cherry': 1, 'peach': 1}
Run Code Online (Sandbox Code Playgroud)