2017-07-29 26 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