14. It's Dangerous to Go Along! Take This: KeyError 'backpack"


#1

I seem to be having an issue where I keep getting the error, line 16 KeyError: 'backpack' yet I have checked the spelling in all places and it matches up exactly. I have done my best to check the rest of my code cause you know there could always be something else causing it.

I have included all my code below

inventory = {
    'gold' : 500,
    'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key
    'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']
}

# Adding a key 'burlap bag' and assigning a list to it
inventory['burlap bag'] = ['apple', 'small ruby', 'three-toed sloth']

# Sorting the list found under the key 'pouch'
inventory['pouch'].sort() 

# Your code here
inventory = {"pocket": ["seashell", "strange berry", "lint"]}

inventory['backpack'].sort()

inventory['backpack'].remove("dagger")

inventory['gold'].add(50)

#2

here:

inventory = {"pocket": ["seashell", "strange berry", "lint"]}
print inventory

you overwrote inventory, so your dictionary no longer contains a backpack

look at how you add burlap bag to dictionary, that might help you


#4

The question was about line 16 and why .add(50) doesn't work. Thanks


#6

overwriting your dictionary and then trying to increase something in a dictionary which is no longer there (because you overwrote), is the first problem.

yes, .add() is not valid, i know that, but i read the code from top to bottom, finding the first issue


#7

I found from the other thread that this is working. It actually means the sum instead of appending a number to the list.
inventory["gold"] = inventory["gold"] + 50


#8

You have the correct answer for line 16. The following is my code, and the only difference is that I used single quotes instead of double quotes around 'dagger':

inventory['backpack'].remove('dagger')

Perhaps you were experiencing a temporary glitch. Try it again.

For line 17, it also worked for me to do:

inventory["gold"] = inventory["gold"] + 50


#9

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.