Reputation: 33
This is a test project from a python book. I am trying to iterate through a list and check if each item is a key in the dictionary. If it is, then add 1 to the dictionary value, if not add the key and then set the value to 1. Here's my code so far:
inv_original = {'gold coin' : 42, 'rope' : 1}
dragonloot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
def addtoinventory(dict_a, addeditems):
for i in addeditems:
if dict_a.has_key(i):
dict_a[str(i)] = dict_a.get(i, 0) + 1
else:
dict_a[str(i)] = 1
return dict_a
inv = addtoinventory(inv_original, dragonloot)
print inv
It seems to work but only for the first item in the list, it doesn't iterate through the rest. Can anyone help please?
Upvotes: 3
Views: 107
Reputation: 6085
Your function returns after completing the first iteration.
def addtoinventory(dict_a, addeditems):
for i in addeditems:
if dict_a.has_key(i):
dict_a[str(i)] = dict_a.get(i, 0) + 1
else:
dict_a[str(i)] = 1
return dict_a # <----- issue here
# ...
You should move the return
statement outside the loop's body by unindenting the line by 4 spaces to fix the issue. You should also consider:
try
/except
block instead of if
/else
,str(i)
call; your list elements are already strings, so it's unnecessary to attempt a string conversion on them, andinventory
instead of dict_a
, and items
instead of addeditems
, which is likely redundant --if it's in the list, it has obviously been added :)The updated code is below:
#!/usr/bin/python
inv_original = {'gold coin' : 42, 'rope' : 1}
dragonloot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
def addtoinventory(inventory, items):
for i in items:
try:
inventory[i] += 1
except KeyError:
inventory[i] = 1
return inventory
#
print addtoinventory(inv_original, dragonloot)
# ...
The code's output is now: {'gold coin': 45, 'rope': 1, 'dagger': 1, 'ruby': 1}
, showing that the gold coin
key has increased by 3
and other key/val pairs have been added, as you expected.
Upvotes: 3