Python-在字典中添加值

时间:2018-09-07 00:40:22

标签: python list dictionary

这是我的代码:

inv = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1}

def display_inventory(inventory):
    #inv = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1}
    print("Inventory:")
    for key, value in inv.items():
            print value, key
    print("")
    print "Number of items is: ",
    print (sum(inv.values())),

def add_to_inventory(inventory, added_items):
    dragon_loot_dict = dict.fromkeys(added_items, 1)
    #print(dragon_loot_dict)
    inventory=dict(inventory.items()+ dragon_loot_dict.items())
    print(inventory)


dragon_loot = ['gold coin', ' dagger', 'gold coin', 'gold coin', 'ruby']

add_to_inventory(inv, dragon_loot)

我刚刚开始学习Python。当我将怪物的战利品添加到我的主要库存时,主要库存的值会更改为怪物库存的值。

如何添加相同项目的值,例如gold coin

2 个答案:

答案 0 :(得分:1)

您可以遍历dragon_loot_dict中的项目,并将值添加到inventory中的相应键中。如果dict.setdefault中还没有这样的密钥,请使用inventory来初始化密钥。

更改:

inventory=dict(inventory.items()+ dragon_loot_dict.items())

收件人:

for k, v in dragon_loot_dict.items():
     inventory[k] = inventory.setdefault(k, int) + v

答案 1 :(得分:0)

您可以迭代战利品并增加库存中的钥匙

inv = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1}
dragon_loot = ['gold coin', ' dagger', 'gold coin', 'gold coin', 'ruby']

def add_to_inventory(inventory, items):
    for item in items:
         # get count of item in inventory, or 0 if item is not in inventory
         item_count = inventory.get(item, 0)
         # update item count in inventory
         inventory[item] = item_count + 1
    print(inventory)

add_to_inventory(inv, dragon_loot)

结果:

#inv = {'rope': 1, 'torch': 6, 'gold coin': 45, 'dagger': 2, 'ruby':1}