Skip to content

Python dictionary update value if the key exists | Example code

  • by

Use the “in” keyword to check if keys exist. If exist then update the value of the dictionary in Python. If the key exists, we update its value by assigning a new value to the key using the assignment operator (=).

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

If the key does not exist in the dictionary, assigning a new value to it will create a new key-value pair in the dictionary.

my_dict = {"key1": "value1", "key2": "value2"}

if "key3" in my_dict:
    my_dict["key3"] = "new_value3"

print(my_dict)

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

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Your email address will not be published. Required fields are marked *