Python Tutorial: How to Update a Dictionary in Python

Dhruv Singhal
2 min readMay 7, 2023

--

Python is a popular programming language used for various purposes, including data analysis, web development, and automation. One of the essential data structures in Python is a dictionary, which allows you to store key-value pairs.

If you need to update a dictionary in Python, you can use the update() method. The update() method takes another dictionary as an argument and adds its key-value pairs to the original dictionary. If the original dictionary already contains a key from the new dictionary, its value will be overwritten.

Here’s an example:

d1 = {1: 1, 2: 2}
d2 = {2: 'ha!', 3: 3}
d1.update(d2)
print(d1)

In this example, we have two dictionaries, d1 and d2. d1 contains the keys 1 and 2, while d2 contains the keys 2 and 3. When we call the update() method on d1 with d2 as the argument, the values from d2 are added to d1. Since d2 contains the key 2, the value of 2 in d1 is overwritten with 'ha!'.

The output of the above code will be:

{1: 1, 2: 'ha!', 3: 3}

As you can see, the value of 2 in the d1 dictionary has been updated to 'ha!'.

The update() method is a useful way to merge two dictionaries in Python. However, if you need to update only a single key-value pair in a dictionary, you can use the square bracket notation to assign a new value to a specific key.

d = {'foo': 'bar', 'baz': 'qux'}
d['foo'] = 'spam'
print(d)

This will output:

{'foo': 'spam', 'baz': 'qux'}

In this example, we update the value of the 'foo' key in the d dictionary to 'spam'.

In summary, the update() method is a powerful way to update dictionaries in Python. It allows you to merge two dictionaries and update the values of existing keys. If you need to update a single key-value pair, you can use the square bracket notation to assign a new value to a specific key.

That’s it for this tutorial on how to update a dictionary in Python! We hope you found it helpful. Keep coding and exploring the endless possibilities of Python!

Any suggestions and comments would be greatly appreciated. If you found this article helpful, please like and share it with others. Don’t forget to follow me to stay up-to-date on my latest articles. Thank you for taking the time to read this!

--

--

Dhruv Singhal

Data engineer with expertise in PySpark, SQL, Flask. Skilled in Databricks, Snowflake, and Datafactory. Published articles. Passionate about tech and games.