【发布时间】:2022-08-21 11:49:56
【问题描述】:
我有两本词典:
fruit1 = {\'apple\': 3, \'banana\': 1, \'cherry\': 1}
fruit2 = {\'apple\': 42, \'peach\': 1}
我想要的最终结果是:
inv3 = {\'apple\': 45, \'banana\': 1, \'cherry\': 1, \'peach\': 1}
到目前为止,我已经尝试过这个示例代码,因为这个输出看起来与我想要的几乎相似,除了它没有按照我想要的方式打印出来而是关闭:
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)
输出将是这样的:
[{\'apple\': 3, \'orange\': 1}, {\'apple\': 42, \'orange\': 1}]
当我尝试使用示例代码输入我的 2 个字典时:
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)
我收到此错误消息:
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\'
我的问题是:
- 如何在不导入任何模块的情况下获得我想要的输出?我只在第 5 章:自动化无聊的东西中的字典和数据结构
- 为什么会出现 KeyError:\'banana\'?
谢谢!
标签: python list dictionary key-value