gpt4 book ai didi

python - 从列表项向字典添加新键时出错

转载 作者:太空宇宙 更新时间:2023-11-04 10:00:01 26 4
gpt4 key购买 nike

我正在研究自动化无聊的东西,这是第 5 章中的第二个项目。出于某种原因,在调用向字典添加项目的函数后,我的字典变成了“无”。这是我的代码:

def displayInventory(anInventory):
item_total = 0
print("Inventory: \n")
for i, j in anInventory.items():
print(str(j) + " " + i)
item_total += j
print("\nTotal number of items: " + str(item_total))

def addToInventory(inventory, addedItems):
for i in addedItems:
if i in inventory:
inventory[i] += 1
else:
inventory[i] = 1

inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)

displayInventory(inv)

我已将问题缩小到 addToInventory 函数,因为 displayInventory 函数本身可以正常工作。如果我在创建 inv 字典的正下方添加打印语句,它会打印字典。但是,如果我在调用 addToInventory 函数之后立即添加 print 语句,它会打印“None”。

我非常有信心该功能运行良好,因此,如果您能帮助指出我的错误,我将不胜感激。谢谢!

最佳答案

您的 addToInventory 函数不返回任何内容,因此您在此行分配 None 值:

inv = addToInventory(inv, dragonLoot)

用简单的方法调用替换赋值:

addToInventory(inv, dragonLoot)

关于python - 从列表项向字典添加新键时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44058699/

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