Reputation: 49
I have the following problem:
Imagining that I killed a dragon and it drops loot, how do I update my inventory from the loot? I figured how to append if the loot does not exist in the inventory but if they already there, I am not sure how to update it.
Here are the codes:
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)
Upvotes: 2
Views: 184
Reputation: 133
You can use the following sample code ...
def addstuff(inventory, additem):
for newitem in additem:
if newitem in inventory:
inventory[newitem] += 1
else:
inventory[newitem] = 1
Upvotes: 2
Reputation: 8583
You should have a look at 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)
Upvotes: 5