Why is there an issue when I add pocket to the dictionary?


#1

Question

Why is there an issue when I add pocket to the dictionary?

Answer

There are two ways we’ve seen to add a key-value pair to an existing dictionary:

  1. Adding it into the existing dictionary by typing out the key and value pair, like so:
inventory = {
  'gold' : 500,
  'pouch' : ['flint', 'twine', 'gemstone'], 
  'backpack' : ['xylophone','dagger', 'bedroll','bread loaf'],
  'new_key_name' : "New value!"
  1. Or accessing the dictionary with a new key and assigning a value to it, like this:
inventory['new_key_name'] = "New value!"

The most common mistake with the first method is missing the comma at the end of the last item in the existing dictionary. Be sure to always have a comma after a dictionary value if you’ve got another key after it!


FAQ: Learn Python: Python Lists and Dictionaries - It's Dangerous to Go Alone! Take This
#2

You can also have the code since the instruction says add not change the value:

inventory['gold] = inventory[‘gold’] + 50