Alan Williams - 1 year ago 93
Python Question

# Algorithmic error in 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:

# dictionary data structure

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

#Iterate through the list
#if key not in the dictionary, add to the dictionary and set its value to zero
inventory.setdefault(k,0)
inventory[k] = inventory[k] + 1
print(str(inventory[k]))

def displayInventory(inventory):
print('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))

displayInventory(stuff)
``````

It says there are 41 gold coins, even though obviously there should be 42: the original 40 from
`stuff`
plus two more in
`dragonLoot`
.

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]).