How to append a value in a dictionary

I have the following dictionary called inventory and I am trying to append the “gold” entry list to be equal to inventory[‘gold’] = [500,50]. Why is my code not working?

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

inventory['gold'].append(50)

Traceback (most recent call last): File “python”, line 7, in <module> AttributeError: ‘int’ object has no attribute ‘append’

Also, when I try to update the value in inventory[‘gold’] to an new variable as such, I get an error as shown below:

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

inventory['gold'][0]+=23

the error I get is

Traceback (most recent call last): File “python”, line 7, in <module> TypeError: ‘int’ object has no attribute ‘getitem

That’s not a list

1 Like

Ok, so how can I do what I want to do. Do I have to redefine ‘gold’ as such:

inventory['gold'] = [500, 50]

Also, why cannot I update the existing value using:

inventory['gold'][0]+=23

Hi @mghanem8800,

When asking for help regarding an exercise, it is best to provide a link to that exercise. It appears that you are asking about It’s Dangerous to Go Alone! Take This.

If that is the case, this instruction relates to what you are doing:

Add 50 to the number stored under the 'gold' key

Here is where you stored a number under the 'gold' key:

inventory = {
  'gold' : 500,

The instruction is asking you to perform an operation that replaces the value stored at that key by a value that is 50 greater than that value. It is not asking you to replace that value by a list. When all is done, that key should still be associated with a single int.

Instead of trying to do this, which is an operation that cannot be performed on an int:

inventory['gold'].append(50)

… perform an operation that increases the value stored at that key by 50.

Edited on December 29, 2018 to clarify the fact that inventory['gold'] originally referred to an int, and should continue to do so.