Python Dictionary Update Example

1. Introduction

In Python, dictionaries are mutable collections of key-value pairs. Updating a dictionary is a common operation, and the Python dictionary method update() makes it possible to modify a dictionary by adding new key-value pairs or changing the value of existing keys.


The update() method updates a dictionary with elements from another dictionary object or an iterable of key-value pairs. It does not return a new dictionary; instead, it modifies the original dictionary in place.

2. Program Steps

1. Initialize two dictionaries, one with the original content and another with the content to be added or updated.

2. Use the update() method to modify the original dictionary with the second one.

3. Print the updated dictionary to show the changes.

3. Code Program

# Original dictionary
original_dict = {'a': 1, 'b': 2}

# Dictionary with updates
updates = {'b': 3, 'c': 4, 'd': 5}

# Update the original dictionary with the updates dictionary

# Print the updated dictionary
print(f"Updated dictionary: {original_dict}")


Updated dictionary: {'a': 1, 'b': 3, 'c': 4, 'd': 5}


1. original_dict starts with two key-value pairs: 'a': 1 and 'b': 2.

2. updates contains three key-value pairs, where 'b': 3 is meant to update the existing value of 'b' in original_dict, and 'c': 4, 'd': 5 are new entries.

3. The update() method is called on original_dict, passing in updates. This adds the new key-value pairs to original_dict and updates the value of any existing key.

4. The final print statement displays original_dict after the update, highlighting the changes: the value of 'b' is now 3, and two new key-value pairs have been added.