Alan Williams Alan Williams - 1 year ago 65
Python Question

I am having trouble with my python program

When I run it, the number of gold coins is only incremented by one, despite the fact that there are three additional gold coins. I do not know what is wrong with my logic. I have created two functions; addToInventory which takes a dictionary as the first parameter and a list as the second parameter. The function adds the key to the dictionary if the key does not exist in the dictionary and increments the value by one. The displayInventory method prints the key/values from the dictionary. Here is my source code: - a function that displays the inventory from a

dictionary data structure

stuff = {'rope': 1, 'torch': 6, 'gold coin': 40, 'dagger': 1, 'arrow': 12}
dragonLoot = {'gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'}

def addToInventory(inventory, addedItems):
#Iterate through the list
for k in addedItems:
#if key not in the dictionary, add to the dictionary and set its value to zero
inventory[k] = inventory[k] + 1

def displayInventory(inventory):
itemTotal = 0
#iterate through the dictionary and print the key/values
for k, v in inventory.items():
print(k + ': ' + str(v))
itemTotal = itemTotal + v
print ('Total number of items: ' + str(itemTotal))

addToInventory(stuff, dragonLoot)

Answer Source

When you define dragonLoot, you're defining a set. Sets are orderless and will only have one of a given term. In python, curly braces are used to define either dictionaries or sets- if it's key : value pairs, it's a dict, otherwise it's a set. To keep order and numbering, us either a tuple (defined using (foo,bar,coin,) form typically) or a list (defined using [foo, bar, coin]).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download