从数组向字典中添加项时,我得到一个错误??Python3.x
当我这样做的时候,它会返回这样一个错误从数组向字典中添加项时,我得到一个错误??Python3.x,python,arrays,python-3.x,dictionary,for-loop,Python,Arrays,Python 3.x,Dictionary,For Loop,当我这样做的时候,它会返回这样一个错误 stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} def displayInventory(inventory): print("Inventory:") item_total = 0 for k, v in inventory.items(): print(str(v) + " " + k)
stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
def displayInventory(inventory):
print("Inventory:")
item_total = 0
for k, v in inventory.items():
print(str(v) + " " + k)
item_total += v
print("Total number of items: " + str(item_total) + '\n')
displayInventory(stuff)
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = {'gold coin': 42, 'rope': 1}
def addToInventory(ram, addedItems):
for itemindex in addedItems:
if itemindex not in ram:
ram[itemindex] = 0
ram[itemindex] = ram[itemindex] + 1
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)
目录:
1根绳子
6火炬
1把匕首
12箭头
项目总数:62
库存:
回溯(最近一次呼叫最后一次):
文件“python”,第33行,在
displayInventory中第8行的文件“python”
AttributeError:“非类型”对象没有属性“项”
考虑到当您将
inv
更改为'abc'
或除inv以外的任何内容时,错误消失,代码运行平稳,这是没有意义的。您将inv
传递到显示库存
,但由于添加到库存
不会返回任何内容,inv
是None
,因此没有属性items()
请复制粘贴控制台输出,不要发布其图像。出现错误的原因是addToInventory
没有显式返回内容,因此返回None
@PaulHanamon当答案解决问题时,可以单击旁边的绿色勾号。它让其他人知道这是一个有效的答案,给你2rep,给回答者15rep
Inventory:
1 rope
6 torch
1 dagger
12 arrow
Total number of items: 62
Inventory:
Traceback (most recent call last):
File "python", line 33, in <module>
File "python", line 8, in displayInventory
AttributeError: 'NoneType' object has no attribute 'items'
inv=addToInventory(inv, dragonLoot) #inv=None since addToInventory returns nothing
displayInventory(inv) #passing it None
for k, v in inventory.items(): #None.items() is obviously invalid, creates error