Append a dictionary to a list in Python

avatar

Borislav Hadzhiev

Wed Jun 22 20222 min read

banner

Photo by Max

Append a dictionary to a list in Python #

To append a dictionary to a list:

  1. Use the copy() method to create a shallow copy of the dictionary.
  2. Use the list.append() method to append the copy to the list.
  3. The list will contain the dictionary by value, and not by reference.
main.py
my_dict = {'name': 'Alice', 'age': 30} my_list = [] dict_copy = my_dict.copy() # 👈️ create copy my_list.append(dict_copy) print(my_list) # 👉️ [{'name': 'Alice', 'age': 30}]

We used the copy.copy method to create a shallow copy of the dictionary.

This is necessary because if we append the dict object to the list directly, we are appending a reference to the same dict object (same location in memory).

Here is an example of how this could go wrong.

main.py
my_dict = {'name': 'Alice', 'age': 30} my_list = [] my_list.append(my_dict) my_list[0]['name'] = 'Bob' print(my_list) # 👉️ [{'name': 'Bob', 'age': 30}] print(my_dict) # 👉️ {'name': 'Bob', 'age': 30}

Notice that after updating the name key of the dictionary in the list, we also updated the name key in the dictionary.

The reason for this is - we didn't create a copy, so we added a reference to the same dictionary in the list.

If you have a dictionary with nested key-value pairs, create a deep copy instead.

main.py
import copy my_dict = {'name': 'Alice', 'address': {'country': 'Austria'}} my_list = [] dict_copy = copy.deepcopy(my_dict) # 👈️ create deep copy my_list.append(dict_copy) print(my_list) # 👉️ [{'name': 'Alice', 'address': {'country': 'Austria'}}]

The copy.deepcopy method creates a deep copy of the provided object.

You only need to use copy.deepcopy if your dictionary contains other objects, like lists, class instances or nested dictionaries.

Now we no longer have the issue that updating a value in the dictionary in the list updates the same value in the other dictionary.

main.py
import copy my_dict = {'name': 'Alice', 'address': {'country': 'Austria'}} my_list = [] dict_copy = copy.deepcopy(my_dict) # 👈️ create deep copy my_list.append(dict_copy) my_list[0]['address']['country'] = 'Belgium' print(my_list[0]['address']['country']) # 👉️ Belgium print(my_dict['address']['country']) # 👉️ Austria

We updated the dictionary in the list, but the same value in the original dictionary remains unchanged.

The reason for this is - we created a copy of the original dictionary and added the copy to the list, therefore we added the dictionary to the list by value, and not be reference.

The dictionary that is in the list is stored at a completely different location in memory than the original dictionary and they are 2 separate objects.

Use the search field on my Home Page to filter through my more than 1,000 articles.