How to update the value of a key in a dictionary in Python?

You can simply specify another value to the existed key:

t = {}
t['A'] = 1
t['B'] = 5
t['C'] = 2

print(t)

{'A': 1, 'B': 5, 'C': 2}

Now let's update one of the keys:

t['B'] = 3

print(t)

{'A': 1, 'B': 3, 'C': 2}

Well you could directly substract from the value by just referencing the key. Which in my opinion is simpler.

>>> books = {}
>>> books['book'] = 3       
>>> books['book'] -= 1   
>>> books   
{'book': 2}   

In your case:

book_shop[ch1] -= 1

You are modifying the list book_shop.values()[i], which is not getting updated in the dictionary. Whenever you call the values() method, it will give you the values available in dictionary, and here you are not modifying the data of the dictionary.


d = {'A': 1, 'B': 5, 'C': 2}
d.update({'A': 2})

print(d)

{'A': 2, 'B': 5, 'C': 2}