Python dictionary update value if the key exists | Example code

Use the “in” keyword to check if keys exist. If exist then update the value of the dictionary in Python.

Example dictionary update value if the key exists in Python

Simple example code update value for a given key in the dictionary.

d = {"key1": 10, "key2": 23}

if "key2" in d:
    d.update({"key2": 20})

print(d)

Output:

Python dictionary update value if key exists

Do comment if you have any doubts and suggestions on this Python dictionary update topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.