繁体   English   中英

如何从列表项更新字典?

[英]How do I update dictionary from items of list?

我有以下问题:

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

以下是代码:

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)

你应该看一下计数器

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)

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM