如何从列表项更新字典?

时间:2017-07-29 10:06:53

标签: python list dictionary

我有以下问题:

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

以下是代码:

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)

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:2)

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

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