我有两个词典,一个代表玩家库存,另一个代表龙库存。我试图把这两本词典合并起来。然后将这两个词典显示为玩家的新库存。我在下面添加了我的代码并且我一直收到以下错误。
Traceback (most recent call last):
File "/Users/DakotaDickey/Documents/Python Projects /Examples/FantasyGameAddToInventory.py", line 38, in <module>
displayInventory(inv)
File "/Users/DakotaDickey/Documents/Python Projects /Examples/FantasyGameAddToInventory.py", line 27, in displayInventory
for k, v in inventory.items():
AttributeError: 'NoneType' object has no attribute 'items'
我的代码:
#FantasyGameAddToInventory
def addToInventory(inventory, addedItems):
addedItemsdict = {}
for item in addedItems:
x = addedItems.count(item)
if item not in addedItemsdict:
addedItemsdict[item] = 1
else:
addedItemsdict[item] = x
for k, v in addedItemsdict.items():
if k in inventory:
x = inventory[k]
inventory[k] = v + x
else:
inventory[k] = v
inv = inventory
print(inv)
def displayInventory(inventory):
print('Inventory:')
item_total = 0
for k, v in inventory.items():
print(k,v)
item_total = item_total + v
print("Total number of items: " + str(item_total))
inv = {'gold coin' : 42 , 'rope': 1}
dragonLoot = ['gold coin', 'dagger' , 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)
我想要产生的输出如下。 库存:
45金币
1根绳子
1 ruby
1 dagger
项目总数:48
答案 0 :(得分:2)
您的功能addToInventory()
会返回您None
分配的inv
:
inv = addToInventory(inv, dragonLoot)
现在inv
设置为None
,您将其传递给displayInventory()
。
在return inv
的末尾添加addToInventory()
。
请记住,打印与返回不是一回事;打印将数据写入终端,函数的调用者不接收该数据。
答案 1 :(得分:0)
或者,您可以将两个字典压缩在一起:
inv = zip(inventory, dragonLoot)
答案 2 :(得分:0)
这是编写addToInventory(inventory,addItems)函数的一种简短得多的方法:
def addToInventory(inventory, addedItems):
for k in addedItems:
if k not in inventory:
inventory.setdefault(k, 1)
else:
inventory[k] += 1
return inventory