'''
这个代码段有两个函数,
第一个函数displayInventory(Inventory)用于展示字典。
键是物品名称,值是物品数量。展示模式是v个k。
第二个函数addToInventory(inventory,addedItems)用于更新字典。
更新方式是遍历列表,对照字典键,有就+1,没有就加进去。
'''
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))
def addToInventory(inventory,addedItems):#加进清单,就是更新字典
for i in addedItems:#遍历列表addedItems
if i in inventory:
inventory[i]+=1
else:
inventory[i]=1
return inventory#返回更新好的字典
inv={'gold coin':42,'rope':1}
dragonLoot=['gold coin','dragger','gold coin','gold coin','ruby']
inv=addToInventory(inv,dragonLoot)#返回更新好的字典到inv
displayInventory(inv)#展示字典inv
上面这是 inventorypy 文件