2017-07-29 19 views
2

我有以下问题:如何更新列表项目的字典?

想象一下,我杀了一条龙并且它掉落了战利品,我该如何从战利品中更新我的库存?我想如何追加如果战利品不存在库存,但如果他们已经在那里,我不知道如何更新它。

这里是代码:

UserInventory = {'rope': 1, 'torch':6, 'gold coin':42, 'dagger': 1, 'arrow': 12} 

def showstuff(storeno): 
items_total = 0 
for k, v in storeno.items(): 
    print('Item :' + k + '---' + str(v)) 
    items_total = items_total + v 
print('Total Items:' + str(items_total)) 

'''def addstuff(inventory, additem): 
    I'm not sure what to do here 

dragonloot = ['gold coin', 'gold coin', 'rope'] 
addstuff(UserInventory, dragonloot)''' 
showstuff(UserInventory) 

回答

5

你应该看看Counters

from collections import Counter 

inventory = {'rope': 1, 'torch':6, 'gold coin':42, 'dagger': 1, 'arrow': 12} 
inventory_ctr = Counter(inventory) 

update = ['rope', 'torch'] 
update_ctr = Counter(update) 

new_inventory_ctr = inventory_ctr + update_ctr 

print(new_inventory_ctr) 
+0

无需创建3个计数器。 'inventory_ctr.update(['rope','torch'])'会做。 –

+0

非常感谢!现在我知道一个新的Python模块! – Kinghin245

2

您可以使用下面的示例代码...

def addstuff(inventory, additem): 
    for newitem in additem: 
     if newitem in inventory: 
      inventory[newitem] += 1 
     else: 
      inventory[newitem] = 1 
+0

谢谢你的回答!这个示例代码就是我想要的! – Kinghin245