我正在通过Automate the Boring Stuff,这是第5章中的第二个项目。出于某种原因,我的字典在调用添加项目的函数后变为“None”一本字典。这是我的代码:将新键添加到列表项中的字典时出错
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函数后立即添加打印语句,则会打印“无”。
我非常有信心该功能运行良好,所以我会很感激任何帮助指出我的错误。谢谢!
似乎[python]队列对我来说太快xD –