(Apr-22-2017, 05:44 PM)ichabod801 Wrote:for item in dragonLoot: stuff[item] = stuff.get(item, 0) + 1This works better with a defaultdict, then you can just add one to the key directly, without having to do the get with a default value of zero.
tried it and this happens:
stuff = {'rope' : 1, 'torch' : 6, 'gold coin' : 42, 'dagger' : 1, 'arrow' : 12} def displayInventory(inventory): print('Inventory:') item_total = 0 for k, v in inventory.items(): print(str(v) + ' ' + k) item_total += v print('Total number of items: ' + str(item_total)) def addToInventory(inventory, addedItems): for item in addedItems: inventory[item] = inventory.get(item, 0) + 1 dragonLoot = ['gold coin', 'dagger', 'gold coin', 'ruby'] stuff = addToInventory(stuff, dragonLoot) displayInventory(stuff)
Error:/usr/bin/python3.5 /root/PythonProjects/AutomateTheBoringStuff/inventory.py
Inventory:
Traceback (most recent call last):
File "/root/PythonProjects/AutomateTheBoringStuff/inventory.py", line 18, in <module>
displayInventory(stuff)
File "/root/PythonProjects/AutomateTheBoringStuff/inventory.py", line 6, in displayInventory
for k, v in inventory.items():
AttributeError: 'NoneType' object has no attribute 'items'
Process finished with exit code 1
Something like this is what I was thinking???def addToInventory(inventory, addedItems): for item in addedItems: if item in inventory.keys(): inventory[item] += 1 print(inventory) return inventory elif item not in inventory.keys(): inventory[item] = 1 print(inventory) return inventory dragonLoot = ['gold coin', 'dagger', 'gold coin', 'ruby'] stuff = addToInventory(stuff, dragonLoot)
When i add return inventory to the function it doesn't add all the inventory in dragonLoot:
stuff = {'rope' : 1, 'torch' : 6, 'gold coin' : 42, 'dagger' : 1, 'arrow' : 12} def displayInventory(inventory): print('Inventory:') item_total = 0 for k, v in inventory.items(): print(str(v) + ' ' + k) item_total += v print('Total number of items: ' + str(item_total)) def addToInventory(inventory, addedItems): for item in addedItems: inventory[item] = inventory.get(item, 0) + 1 return inventory dragonLoot = ['gold coin', 'dagger', 'gold coin', 'ruby'] stuff = addToInventory(stuff, dragonLoot) displayInventory(stuff)
Output:/usr/bin/python3.5 /root/PythonProjects/AutomateTheBoringStuff/inventory.py
Inventory:
1 rope
43 gold coin
12 arrow
6 torch
1 dagger
Total number of items: 63
Process finished with exit code 0