I'm currently doing the second exercise found here. https://automatetheboringstuff.com/chapter5 ("List to Dictionary Function for Fantasy Game Inventory")
The task is to add the items from a list to a dictionary.
For some weird reason, my for loop is not looping through the whole list. Can you help me to understand why?
def addToInventory(inventory, addedItems): for i in addedItems: if i in inventory: inventory[i] = inventory[i] + 1 else: inventory[i] = 1 return inventory inv = {'gold coin': 42, 'rope': 1} dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] inv = addToInventory(inv, dragonLoot) print(inv)
When I run this code, the result is "{'rope': 1, 'gold coin': 43}" So the value of the gold coin key is increased by 1 (not by 3 which it is supposed to), and 'dagger' and 'ruby' are ignored.
I have found a working solution elsewhere, but I really want to understand why this code doesn't work.
Thanks in advance.