Reputation: 3
I'm a beginner working on the Automate the boring stuff with Python book. I'm stuck on this practice problem. The instructions are as follows:
List to Dictionary Function for Fantasy Game Inventory:
Imagine that a vanquished dragon’s loot is represented as a list of strings like this:
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
Write a function named addToInventory(inventory, addedItems)
, where the
inventory parameter is a dictionary representing the player’s inventory (like
in the previous project) and the addedItems
parameter is a list like dragonLoot
. The addToInventory()
function should return a dictionary that represents the updated inventory. Note that the addedItems
list can contain multiples of the same item. Your code could look something like this:
def addToInventory(inventory, addedItems):
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)
The previous program (with your displayInventory()
function from the
previous project) would output the following:
Inventory:
45 gold coin
1 rope
1 ruby
1 dagger
Total number of items: 48
My code is as follows
def addtoinventory(inventory,lootlist):
for i in range(len(lootlist)):
if lootlist[i] in inventory:
inventory[lootlist[i]] = inventory[lootlist[i]] + 1
else:
inventory.setdefault(lootlist[i],1)
return inventory
def displayinventory(inventory):
total_items = 0
for k,v in inventory.items():
print(k + ' : ' + str(v))
total_items = total_items + v
print("Total number of items: " + str(total_items))
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addtoinventory(inv, dragonLoot)
displayinventory(inv)
My output is like this:
gold coin : 45
ruby : 1
rope : 1
Total number of items: 47
What am I doing wrong?
Upvotes: 0
Views: 5321
Reputation: 1
You had several indentation problems and the print of the displayinventory
function
Compare with this:
def addtoinventory(inventory,lootlist):
for i in range(len(lootlist)):
if lootlist[i] in inventory:
inventory[lootlist[i]] = inventory[lootlist[i]] + 1
else:
inventory.setdefault(lootlist[i],1)
return inventory
def displayinventory(inventory):
total_items = 0
for k,v in inventory.items():
# Change this line
# print(k + ' : ' + str(v))
print('%d %s' % (v,k))
# Or print(v,k)
# Or print(f'{v} {k}')
total_items = total_items + v
print("Total number of items: " + str(total_items))
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addtoinventory(inv, dragonLoot)
displayinventory(inv)
Additionally, I leave you my solution to that exercise:
def displayInventory(inventory):
print("Inventory:")
item_total = 0
for k, v in inventory.items():
print('%s %s' % (v,k))
item_total += v
print("Total number of items: %s" % item_total)
def addToInventory(inventory, addedItems):
for k in addedItems:
inventory.setdefault(k,0)
inventory[k] += 1
return inventory
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)
Output:
Inventory:
45 gold coin
1 rope
1 dagger
1 ruby
Total number of items: 48
Upvotes: 0
Reputation: 1
One important thing to note about this exercise is that it uses the function of the previous exercise and the output given on that exercise contains plural forms of items in inventory depending on the number of items so here is my version of the two exercises which follow the rules I use the inflect module for converting words to plural from Here Is The Code:
import inflect #for plural forms of items in inventory
p = inflect.engine()
stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
def displayInventory(inventory): #this is the previous exercise as we need this function to do this exercise
print("Inventory:")
item_total = 0
for k, v in inventory.items():
if v > 1: #'v' is huch of given item there is
key = p.plural(k) #if there is more than 1 of the given item 'k' converts it into plural form
else:
key = k #if there is only 1 of the item then no need for plural form
print('' + str(v) + ' ' + key ) #prints the number of items + the item name example: 12 torches or 1 ruby
item_total += v #v is added to item_total
print("Total number of items: " + str(item_total))
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
def addToInventory(inventory, addedItems):
for k in addedItems: #loops over the valus in the list addedItems which is dragonLoot in this case
if k in inventory.keys(): #if the current value of k is in the keys of inventory which is inv in this case the following code is executed this means that the dragons loot has the item 'k'
inventory[k] += 1 # 1 is added to the the key value of 'k' this means that the user got 1 more of the loot item
else:
inventory.setdefault(k, 1) # if k is not in the inventory then k is added to it and the value is set to 1
return inventory #then the edited inventory dict is returned
inv = addToInventory(inv, dragonLoot) # the function is called on inv and dragonLoot
displayInventory(inv) #the displayInventory fuction is called on inv dict
I hope this code works fine as I'm also a beginner "Thank You"
Upvotes: 0
Reputation: 1
from collections import Counter
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
dl = (dict(Counter(dragonLoot)))
def addToInventory(inventory, addedItems):
for key, v in addedItems.items():
if key not in inventory:
inventory.setdefault(key, 1)
elif key in inventory:
inventory[key] = inventory[key] + v
return inventory
addToInventory(inv,dl)
print(inv)
Upvotes: 0
Reputation: 1
def add(inventory,items):
for j in items:
for i ,k in inventory.copy().items():
if i==j:
inventory[i]=k+1
else:
inventory.setdefault(j,1)
print(inventory)
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
add(inv,dragonLoot)
I think this will be the best approach
Upvotes: 0
Reputation: 1
This is how i did it. I think this is a clean solution for the addToInventory() function. What do you think? Or did i missed something?
PlayerInventory = {"gold coin": 42, "rope": 1}
dragonLoot = ["gold coin", "dagger", "gold coin", "gold coin", "ruby"]
def displayInventory(inventory): # Displays the Inventory
print("Inventory:")
cnt = 0
for k, v in inventory.items():
print(k + " : " + str(v))
cnt += v
print(f"Total number of items: {cnt}")
def addToInventory(inventory, addedItems): # Add items to the provided inventory
for item in addedItems: # Loops trough the provided list.
inventory.setdefault(item, 0) # Checks if the key exists. If not, adds it with a value of 0.
inventory[item] += 1 # Adds 1 to the value.
return inventory # returns the complete Dictionary
PlayerInventory = addToInventory(PlayerInventory, dragonLoot)
displayInventory(PlayerInventory)
Upvotes: 0
Reputation: 1
This is how I figured it out. wanted to share since is the first one I did without help. hope it helps and all feedback is welcome.
`
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = {'gold coin':42, 'rope': 1}
def addToInventory(inventory, addedItems):
for loot in addedItems:
inventory.setdefault(loot, 0)
for k, v in inventory.items():
if loot == k:
inventory[loot] = v + 1
def displayInventory(inventory):
totalItems = 0
for k, v in inventory.items():
print(str(v) + '---' + str(k))
totalItems += v
print('Total number of items: '+ str(totalItems))
addToInventory(inv, dragonLoot)
displayInventory(inv)
`
Upvotes: 0
Reputation: 17
Here's my solution:
# inventory.py
# 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 i in addedItems:
#copy() is for to avoid RuntimeError: dictionary changed size during iteration
for k, v in inventory.copy().items():
if k == i:
inventory[k] = v + 1
if i not in inventory.keys():
inventory[i] = 1
return inventory
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)
# displayInventory(stuff)
Upvotes: 0
Reputation: 11
items={'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
def displayInventory(*inventory):
total_items = 0
for i, j in items.items():
print(j, i)
total_items += j
print("Total number of items: " + str(total_items))
displayInventory()
Upvotes: -1
Reputation: 1
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
def addToInventory(inventory, addedItems):
for i in range(len(addedItems)):
if addedItems[i] in inventory:
inventory[addedItems[i]] = inventory[addedItems[i]] + 1
else:
inventory.setdefault(addedItems[i],1)
return inventory
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)
Upvotes: 0
Reputation: 73
i just got into the book and here how I solved it, seems pretty simple:
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
def addToInventory(backpack, added_items):
for i in added_items:
if i in backpack:
backpack[i] += 1
else:
count = 0
count += 1
backpack[i] = count
return backpack
Upvotes: 0
Reputation: 1
You're searching for range in Dictionary and your code has issues with unexpected indent
playerInventory = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
def addToInventory(inventory, addedItems):
for i in addedItems:
if i not in inventory:
inventory.setdefault (str(i), 1)
else:
inventory[i] = inventory[i] + 1
return inventory
playerInventory = addToInventory(playerInventory, dragonLoot)
print(playerInventory)
Upvotes: 0
Reputation: 1
Try the following:
def addToInventory(dragonLoot,inv):
count={}
for item in dragonLoot:
count.setdefault(item,0)
count[item]=count[item]+1
for k in count.keys():
if k in inv.keys():
inv[k]=inv[k]+count[k]
print(inv)
Upvotes: 0
Reputation: 1
def displayInventory(inventory):
print("Inventory:")
item_total = 0
for k, v in inventory.items():
item_total += v
print(str(v) + ' ' + str(k))
print("Total number of items: " + str(item_total))
def addToInventory(inventory, addItems):
for k in range(len(addItems)):
inventory.setdefault(addItems[k], 0)
inventory[addItems[k]] += 1
return(inventory)
inventory = {'rope': 1, 'torches': 6, 'gold coins': 42, 'daggers': 28, 'arrows': 12, 'knives': 50}
dragonLoot = ['gold coins', 'daggers', 'gold coins', 'gold coins', 'ruby']
updatedInventory = addToInventory(inventory, dragonLoot)
displayInventory(updatedInventory)
print("Inventory updated.")
Upvotes: 0
Reputation: 11
I copied your code and it worked just fine for me, apart from the items and their numbers being in the wrong order, which is easily fixed if you change the print line to this:
print(str(v)+' : '+k)
Upvotes: 1
Reputation: 1
This is how I solved it. I wasn't able to get rid of the brackets though, and for some reason the pprint didn't work. But this code serves the purpose anyway...
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
#Turn dragonLoot list in to a dictionary:
list={}
for i in dragonLoot:
if i not in list:
list.setdefault(i, 1)
elif i in list:
list[i] = list[i] +1
#Merge dictionaries:
for i, v in list.items():
if i not in inv:
inv.setdefault(i, 1)
elif i in inv:
inv[i]=inv[i]+v
import pprint
print('Inventory: ')
pprint.pprint(inv, width=1)
print('')
total=0
#Count the total number of items:
for i, v in inv.items():
total=total+v
print('Total number of items: ' + str(total))
Upvotes: 0
Reputation: 36
I think your indent of else:
is wrong. You should use if-else, but your code is for-else. The code below works well.
def addtoinventory(inventory,lootlist):
for i in range(len(lootlist)):
if lootlist[i] in inventory:
inventory[lootlist[i]] = inventory[lootlist[i]] + 1
else:
inventory.setdefault(lootlist[i],1)
return inventory
The result is below.
>>> inv = {'gold coin': 42, 'rope': 1}
>>> dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
>>> inv = addtoinventory(inv, dragonLoot)
>>> inv
{'gold coin': 45, 'rope': 1, 'dagger': 1, 'ruby': 1}
Upvotes: 2