Update a dictionary in Python

In Python, you can update a dictionary using a update() method or by directly assigning values to keys.

(1) Using the update() method

The update() method merges the contents of another dictionary or an iterable of key-value pairs into the original dictionary. If a key already exists, its value is overwritten. If a key doesn’t exist, a new key-value pair is added.

For example:

dict1 = {'a': 1, 'b': 2}
dict2 = {'b':3, 'c': 4}

dict1.update(dict2)
print(dict1)

Output:

{'a': 1, 'b': 3, 'c': 4}

You can also pass an iterable of key-value pairs (e.g. a list of tuples).

my_dict = {'a': 1, 'b': 2}

# Updating with a list of tuples
my_dict.update([('c', 3), ('d', 4)])
print(my_dict)

Output:

{'a': 1, 'b': 2, 'c': 3, 'd': 4}

You can also use keyword arguments to update a dictionary.

my_dict = {'a': 1, 'b': 2}

# Updating with keyword arguments
my_dict.update(c=3, d=4)
print(my_dict)

Output:

{'a': 1, 'b': 2, 'c': 3, 'd': 4}

(2) Direct key assignment

You can update a dictionary by directly assigning values to keys. If the key already exists, its value will be updated. If the key doesn’t exist, it will be added to the dictionary.

For example:

my_dict = {'a': 1, 'b': 2}

# Update existing key
my_dict['b'] = 3

# Add new key-value pair
my_dict['c'] = 4

print(my_dict)

Output:

{'a': 1, 'b': 3, 'c': 4}

(3) Using | operator

In Python 3.9 and later, you can use the | operator to merge two dictionaries.

For example:

dict1 = {'a': 1, 'b': 2}
dict2 = {'b':3, 'c': 4}

merged_dict = dict1 | dict2
print(merged_dict)

Output:

{'a': 1, 'b': 3, 'c': 4}

Which method to use?

Use update() method to add or modify multiple items at once.

Use direct key assignment to add or modify a single item.

Use | operator to combine dictionaries.