gpt4 book ai didi

python - 使用整数数据类型向字典添加值

转载 作者:太空宇宙 更新时间:2023-11-03 20:18:03 25 4
gpt4 key购买 nike

我正在尝试创建一个程序来检查某个项目是否在列表中。我收到有关我尝试导入的数据类型的错误。

奇怪的是,我可以在代码开头成功添加相同的数据类型,但在代码后面添加具有相同数据类型的类似数据却失败了。

我尝试使用 dic4.update(str(d)) 而不是 dic4.update(d)

dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}

dic4 = {}

for d in (dic1,dic2,dic3):
dic4.update(d)
# adds all items from dict1,dict2, and dict3 to dic4

print(dic4)

dic5={3:30, 9:45}

for d in dic5:
if d in dic4:
print("Already in set")
else:
print("Added to set")
dic4.update(d)
# error occurs on above line

print(dic4)

我希望将值 {9:45} 添加到字典“dic4”中,如下所示:

{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
Already in set
Added to set
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60, 9: 45}

输出:

{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
Already in set
Added to set
Traceback (most recent call last):
File "C:/Users/19083/AppData/Local/Programs/Python/Python37-32/Dictionary Practice/dictExercise3.py", line 20, in <module>
dic4.update(d)
TypeError: 'int' object is not iterable

最佳答案

试试这个:

for d in list(dic5):
if d in list(dic4):
print("Already in set")
else:
print("Added to set")
dic4[d] = dic5[d]

关于python - 使用整数数据类型向字典添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58328866/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com