How to Append a Dictionary to a List in Python

avatar
Borislav Hadzhiev

Last updated: Feb 18, 2023
3 min

banner

# Table of Contents

  1. Append a dictionary to a list in Python
  2. Appending a dictionary by reference or by value
  3. Create a deep copy when working with nested dictionaries
  4. Appending a dictionary to a list in a for loop

# 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}]

append dictionary to list

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

You may also see examples that use the dict() class to create a shallow copy of the dictionary before appending it to a list.

main.py
my_dict = {'name': 'Alice', 'age': 30} my_list = [] dict_copy = dict(my_dict) # ๐Ÿ‘ˆ๏ธ create copy my_list.append(dict_copy) print(my_list) # ๐Ÿ‘‰๏ธ [{'name': 'Alice', 'age': 30}]

The code sample achieves the same result, but instead of using the dict.copy() method to create a shallow copy of the dictionary, we used the dict() class.

# Appending a dictionary by reference or by value

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.

We didn't create a copy, so we added a reference to the same dictionary in the list.

# Create a deep copy when working with nested dictionaries

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'}}]

create deep copy when working with nested dictionaries

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.

We created a copy of the original dictionary and added the copy to the list, so we added the dictionary to the list by value, and not by reference.

The dictionary that is in the list is stored in a completely different location in memory than the original dictionary.

The two dictionaries are separate objects and mutating one of them doesn't mutate the other.

# Appending a dictionary to a list in a for loop

You can also append a dictionary to a list using a for loop.

main.py
my_list = [] for index in range(5): my_list.append({1: index}) # [{1: 0}, {1: 1}, {1: 2}, {1: 3}, {1: 4}] print(my_list)

We used the range() class to get an iterator of length 5.

On each iteration, we append a new dictionary to the list.

We didn't have to use the dict.copy() method because we create a new dictionary on each iteration.

If you are appending the same dictionary to the list, use the dict.copy() method.

main.py
my_list = [] my_dict = {1: 'abc'} for index in range(5): my_list.append(my_dict.copy()) # [{1: 'abc'}, {1: 'abc'}, {1: 'abc'}, {1: 'abc'}, {1: 'abc'}] print(my_list)

The dictionary is declared outside the for loop, so we had to use the dict.copy() method to avoid appending the same dictionary to the list.

If your dictionary contains nested key-value pairs, use the deepcopy() method instead.

main.py
import copy my_list = [] my_dict = { 'name': 'Bobby', 'address': { 'country': 'Example' } } for index in range(5): my_list.append(copy.deepcopy(my_dict)) # [{'name': 'Bobby', 'address': {'country': 'Example'}}, ...] print(my_list)

The deepcopy method creates a deep copy of the dictionary on each iteration, so the dictionaries in the list are stored in different locations in memory.

Updating a key in one dictionary won't update the key in the other dictionaries.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev