How to update a Python dictionary

Posted in Python by Dirk - last update: Feb 09, 2024

To update a dictionary in Python, you can use the update() method, which merges key-value pairs from another dictionary or any iterable object into the original one. As alternative methods, you can use square bracket notation [], the dict() constructor, or the setdefault() method. update() is generally preferred for larger updates or combining dictionaries, while direct assignment is simpler for specific key-value modifications.

If you want to update a dictionary without overwriting its values, you should use the dictionary.setdefault(), the dictionary will only be updated if the key does not yet exist.

What is a dictionary?

A dictionary in Python is a data structure that stores key-value pairs, where each key must be unique. It is defined using curly braces {} and allows efficient retrieval of values based on their associated keys.

There are several options to update a dictionary in Python:

Using the update() method

The update() method takes a dictionary or any iterable object as an argument and updates the original dictionary with the key-value pairs from the argument. The update()

method is well-suited for updating multiple key-value pairs at once, either from another dictionary or an iterable object.

update() with a Dictionary as Argument

# Using a dictionary to update
original_dict = {'a': 1, 'b': 2}
update_dict = {'b': 3, 'c': 4}
original_dict.update(update_dict)
print(original_dict)

In the example above, it updates the value of 'b' and adds a new key-value pair 'c': 4. The result:

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

The original_dict is updated with the key-value pairs from update_dict. If a key from update_dict already exists in original_dict, the corresponding value is updated; otherwise, a new key-value pair is added.

update() with a list of Tuples as Argument

# Using a list of tuples to update
original_dict = {'a': 1, 'b': 2}
update_tuples = [('b', 3), ('c', 4)]
original_dict.update(update_tuples)
print(original_dict)

As in the previous case, the value of 'b' is modified and a new key-value pair 'c': 4 is added.

The result:

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

The original_dict is updated with key-value pairs from the list of tuples (update_tuples). Each tuple in the list represents a key-value pair, and the update process is similar to the dictionary example.

Important: if a key exists in both the original dictionary and the updating source, the value from the updating source takes precedence.

Using square bracket notation

my_dict = {'a': 1, 'b': 2, 'c': 3}
my_dict['b'] = 5
print(my_dict)

This example updates the value associated with the key 'b' to 5 using square bracket notation.

{'a': 1, 'b': 5, 'c': 3, 'd': 7}

Square bracket notation is typically used for updating individual keys. If you have multiple key-value pairs to update, it can result in repetitive code. When dealing with a large number of updates or when merging multiple dictionaries it is better to use the update()method.

Using dict() constructor

my_dict = {'a': 1, 'b': 2, 'c': 3}
my_dict = dict(my_dict, b=5)
print(my_dict)

The dict() constructor can be used to create a new dictionary, and you can pass existing key-value pairs as well as new ones. In this example, it updates the value of key 'b' to 5.

Output:

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

Unlike update(), the dict() constructor creates a new dictionary rather than updating an existing one. This may not be efficient for in-place updates. Its primary use is to create dictionaries, of to copy existing dictionaries.

Using the setdefault() method

The setdefault() method sets the default value for a key if the key is not present in the dictionary.

my_dict = {'a': 1, 'b': 2, 'c': 3}
my_dict.setdefault('b', 5) # -> this wil not work
my_dict.setdefault('d', 7)
print(my_dict)

In this case, it tries to updates the value of 'b' and adds a new key-value pair 'd': 7.

Output:

{'a': 1, 'b': 5, 'c': 3, 'd': 7}

If the key already exists in the dictionary, the value will be ignored. In the example above, the statement my_dict.setdefault('b', 5)will not do anything - the bkey already exists in the dictionary, and the argument 5of the setdefault() function will be ignored

Using setdefault() allows you to update a key only if it does not already exist, which can be useful in scenarios where you want to avoid explicit key existence checks.

Other articles