close

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

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to update the value of a key in a dictionary in Python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

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

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

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

  2. update the value of a key in a dictionary in Python

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

Method 1

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

Method 2

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

print(d)

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

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read