Reputation: 185
I am still very new to programming, and I ran into a problem here that I cannot seem to find a good answer for. Basically, I made a little program that lets you add and remove items from a dictionary. This is supposed to be like an inventory from an rpg game where you can open a chest and the contents will be added to the inventory, and when you you use items they will be removed from the inventory. I want to set it up where if there are zero or fewer of a particular item in the inventory, that item then disappears from the dictionary all together. This is where I am having some trouble. Here is my completed program
inventory = {}
def add_to_inventory(item_tuple):
inventory[item_tuple[0]]=item_tuple[1]
def add_all_items(tuple_list):
for tup in tuple_list:
if tup[0] not in inventory:
add_to_inventory(tup)
else:
inventory[tup[0]]+=tup[1]
return inventory
def remove_items(item,quantity):
global inventory
updated_inventory={}
for key,value in inventory.items():
if key==item:
value-=quantity
inventory[key]=value
if inventory[key]<= 0:
inventory[key]=0
for key,value in inventory.items():
if value!=0:
updated_inventory[key]= value
inventory=updated_inventory
here is the program at work:
>>> chest=[("healing potion",3),("sword",1),("bread",5),("gold",50)]
>>> inventory
{}
>>> add_all_items(chest)
{'bread': 5, 'healing potion': 3, 'gold': 50, 'sword': 1}
>>> remove_items("bread",3)
>>> inventory
{'bread': 2, 'healing potion': 3, 'gold': 50, 'sword': 1}
>>> remove_items("bread",2)
>>> inventory
{'healing potion': 3, 'gold': 50, 'sword': 1}
>>>
I am pretty happy with how the first two functions look, but my remove_items function looks extremely sloppy, and I know there has to be a better way to do it even though it technically works. I tried using "pop" and "del", however I would get a Runtime error telling me that my dictionary changed size during iteration. So now I had to make a whole new inventory called updated_inventory and eventually after a roundabout process set it equal to "inventory" when it is correct. Like I said I have only been at this for a month, so I am assuming that there is something I could be doing better here, but so far this is the only way that works. I can tell from reading it that it looks poorly designed. Any recommendations on what I could to better? Thanks for the help.
Upvotes: 3
Views: 1212
Reputation: 3806
I don't see why you need to search through the list of items. The point of a dictionary is to have immediate access.
You also don't need to duplicate the dictionary. Instead:
def remove_items(item,quantity):
global inventory
if item not in inventory: #make sure the item is in the inventory first
return
inventory[item] -= quantity
if inventory[item] <= 0: #remove item if the quantity is less than 0
inventory.pop(item,None)
Upvotes: 1