简体   繁体   中英

Python - adding values in dictionary

Here is my code:

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)

I'v just started learning Python. When I'm adding loot from monster to my main inventory, values from main inventory is changing to values from monster inventory.

How can I add values of the same items eg, gold coin ?

You can iterate through the items in dragon_loot_dict and add the values to the corresponding keys in inventory . Use dict.setdefault to initialize the key in case there is no such key yet in inventory .

Change:

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

to:

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

You can iterate the loot and increment the key in your inventory

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)

Result:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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