Skip to main content

How to Append Dictionaries to Lists in Python

Appending dictionaries to lists is a common pattern in Python, but it's crucial to understand how Python handles object references to avoid unintended side effects.

This guide explains how to correctly append dictionaries to lists, covering shallow and deep copying to prevent accidental modifications, and demonstrates techniques for appending within loops.

Appending Dictionaries by Value (Not by Reference)

The key to correctly appending dictionaries to a list is to ensure you're adding copies of the dictionary, not references to the same dictionary object.

Shallow Copy with copy()

Use the copy() method to create a shallow copy of the dictionary before appending it. This works well for dictionaries with simple values (like numbers or strings).

my_dict = {'name': 'Anna', 'age': 23}
my_list = []

dict_copy = my_dict.copy() # Create a shallow copy
my_list.append(dict_copy)

print(my_list) # Output: [{'name': 'Anna', 'age': 23}]
  • The my_dict.copy() will create a new dictionary object.
  • If we append to the list without making a copy, then if we later modify the my_dict object, the changes will also be reflected in the list.

Shallow Copy with dict()

You can also create a shallow copy using the dict() constructor:

my_dict = {'name': 'Anna', 'age': 23}
my_list = []

dict_copy = dict(my_dict) # Create a shallow copy
my_list.append(dict_copy)

print(my_list) # Output: [{'name': 'Anna', 'age': 23}]
  • This achieves the same result as copy(), creating a separate dictionary object.

Deep Copy for Nested Dictionaries

If your dictionary contains nested dictionaries (or other mutable objects like lists), you must use a deep copy to avoid unintended side effects. Use the deepcopy() function from the copy module:

import copy

my_dict = {'name': 'Anna', 'address': {'country': 'Austria'}}
my_list = []

dict_copy = copy.deepcopy(my_dict) # Create a DEEP copy
my_list.append(dict_copy)

my_list[0]['address']['country'] = 'Italy' # Modify the copy

print(my_list[0]['address']['country']) # Output: Italy
print(my_dict['address']['country']) # Output: Austria (original unchanged!)
  • deepcopy() creates a completely independent copy, including all nested objects. If you don't use deep copy, modifying the country for a dictionary inside the list, will also modify the country in my_dict as well.

Appending Dictionaries in a Loop

Creating New Dictionaries Each Iteration

When creating a list of dictionaries within a loop, the simplest (and often safest) approach is to create a new dictionary object on each iteration:

my_list = []

for index in range(5):
my_list.append({1: index}) # New dictionary each time

print(my_list) # Output: [{1: 0}, {1: 1}, {1: 2}, {1: 3}, {1: 4}]

This ensures each dictionary in the list is completely independent.

Copying a Dictionary Within a Loop

If you need to start with a base dictionary and modify it within the loop, create a copy (shallow or deep, depending on the structure) inside the loop:

my_list = []
my_dict = {1: 'abc'}

for index in range(5):
my_list.append(my_dict.copy()) # copy the dictionary

print(my_list) # Output: [{1: 'abc'}, {1: 'abc'}, {1: 'abc'}, {1: 'abc'}, {1: 'abc'}]
note

The important difference is that the copying occurs inside the loop, not before it, to prevent all list elements from pointing to the same dictionary object.

For nested dictionaries use deepcopy():

import copy

my_list = []
my_dict = {
'name': 'Anna',
'address': {
'country': 'Italy'
}
}

for index in range(5):
my_list.append(copy.deepcopy(my_dict)) # Deep copy inside the loop

print(my_list)

Output:

[{'name': 'Anna', 'address': {'country': 'Italy'}}, {'name': 'Anna', 'address': {'country': 'Italy'}}, {'name': 'Anna', 'address': {'country': 'Italy'}}, {'name': 'Anna', 'address': {'country': 'Italy'}}, {'name': 'Anna', 'address': {'country': 'Italy'}}]