Reputation: 39
I want to add a list of items to an existing dictionary, but I am not getting the correct number of items. This is my code.
d = {'rope': 1, 'torch': 6, 'gold coin': 3, 'dagger': 1, 'arrow': 12}
def displayInventory(inventory):
print('Inventory:')
totnum = 0
for k,v in d.items():
print(v, k)
totnum += v
print('Total number of items: ' + str(totnum))
displayInventory(d)
print()
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'ruby']
def addToInventory(inventory, add):
new= dict.fromkeys(add, 1)
for k, v in new.items():
inventory[k] = v
z = addToInventory(d, dragonLoot)
displayInventory(d)
The expected output should be this
Inventory:
1 rope
6 torch
5 gold coin
2 dagger
12 arrow
1 ruby
Total number of items: 27
Upvotes: 0
Views: 179
Reputation: 1167
Consider restructuring and using a Counter
like below:
from collections import Counter
inventory = Counter({'rope': 1, 'torch': 6, 'gold coin': 3, 'dagger': 1, 'arrow': 12})
def displayInventory():
print('Inventory:')
for k, v in inventory.items():
print(v, k)
print(f'Total number of items: {sum(inventory.values())}')
displayInventory()
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'ruby']
print('--Picked up loot!')
inventory.update(dragonLoot)
displayInventory()
Gives:
Inventory:
1 rope
6 torch
3 gold coin
1 dagger
12 arrow
Total number of items: 23
--Picked up loot!
Inventory:
1 rope
6 torch
5 gold coin
2 dagger
12 arrow
1 ruby
Total number of items: 27
This also means that if you can safely check the inventory for items not already in there like:
print(inventory['diamond'])
which gives:
0
(a normal dict would raise a KeyError
).
Upvotes: 1
Reputation: 1408
You might want to use a collections.Counter
. If you use it, your could would look like this:
d = Counter({'rope': 1, 'torch': 6, 'gold coin': 3, 'dagger': 1, 'arrow': 12})
loot = ['gold coin', 'dagger', 'gold coin', 'ruby']
d.update(loot)
print(d)
# Counter('rope': 1, 'torch': 6, 'gold coin': 5, 'dagger': 2, 'arrow': 12, 'ruby':1)
Upvotes: 0
Reputation: 188
This is because the dict.fromkeys(add, 1)
does something else then you think:
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'ruby']
>>> dict.fromkeys(dragonLoot, 1)
{'gold coin': 1, 'ruby': 1, 'dagger': 1}
So it does not count the occurences.
I would change the addToInventory
function to this:
def addToInventory(inventory, add):
for k in add:
inventory[k] = inventory.get(k, 0) + 1
So you loop over the items you found and add it to your inventory
Upvotes: 1