In this tutorial, you’ll learn all the different ways to copy a Python dictionary. While this may seem like a very rudimentary task, there are a number of complexities involved in this. In this tutorial, you’ll learn how to copy a dictionary reference-wise, create shallow copies, and create deep copies.
By the end of this tutorial, you’ll have a strong understanding of:
- Different ways to copy dictionaries in Python
- What the differences between references, shallow copies, and deep copies are
- When you may want to use each of the different methods to copy Python dictionaries
Let’s get started!
Table of Contents
The Quick Answer: Copy a Python Dictionary
If you’re short on time, here is the quick answer to how to copy a dictionary in Python. These items are covered in detail in the sections below:
Method | Notes |
---|---|
= Operator | Creates a pointer to the original dictionary |
.copy() Method | Creates a shallow copy to the dictionary |
deepcopy() Function | Creates a deep copy to the dictionary |
A Quick Recap of Python Dictionaries
Before diving into how to copy Python dictionaries, let’s take a quick look at what Python dictionaries are. Python dictionaries are an ordered collection data type, where data are stored as key:value
pairs.
Think of dictionary keys as the words in dictionaries, where the values are the definitions. Dictionary keys have to be unique and immutable. Dictionary values, meanwhile, can be duplicated and can contain mutable data types like lists.
Let’s see how we can create a dictionary in Python:
# Creating a Python Dictionary
original = {
'a': 1,
'b': 2,
'c': [1,2,3]
}
How to Copy a Python Dictionary Using the = Operator
When we attempt to copy a dictionary using the =
operator, it may seem like we are creating a copy of the dictionary. However, we are really only creating an association to the original dictionary. In fact, we’re only assigning the same dictionary to a second variable.
Let’s see what this looks like:
# Assigning a Dictionary Using the = Operator
original = {'a': 1, 'b': 2, 'c': [1,2,3]}
copied = original
We can confirm that this doesn’t actually copy the dictionary by using the id()
function. This will tell us where in memory the data are stored:
# Checking IDs of Our Dictionaries
original = {'a': 1, 'b': 2, 'c': [1,2,3]}
copied = original
print(id(original))
print(id(copied))
# Returns:
# 140195249225088
# 140195249225088
In the next section, you’ll learn how to create a copy of a dictionary using the .copy()
method.
How to Copy a Python Dictionary Using copy
The simplest way to create a copy of a Python dictionary is to use the .copy()
method. This method returns a shallow copy of the dictionary. Let’s break down what a shallow copy means:
- In a shallow copy, as little as possible is duplicated.
- This means that items are created as references to the original items.
- When primitive data types (such as integers and strings) are modified, the reference to the original dictionary are broken.
- When non-primitive data types are modified, the values are modified in both locations.
Let’s see how this looks in action using our sample dictionary above:
# Copying a Dictionary using .copy()
original = {'a': 1, 'b': 2, 'c': [1, 2, 3]}
copied = original.copy()
print(copied)
# Returns: {'a': 1, 'b': 2, 'c': 3}
We can see that the dictionary was successfully copied. Let’s see what happens when we modify an item in the copied dictionary. Let’s modify the value of key b
in our copied dictionary:
# Modifying Items in a Shallow Copied Dictionary
original = {'a': 1, 'b': 2, 'c': [1,2,3]}
copied = original.copy()
copied['b'] = 99
print(f'{original=}')
print(f'{copied=}')
# Returns:
# original={'a': 1, 'b': 2, 'c': [1, 2, 3]}
# copied={'a': 1, 'b': 99, 'c': [1, 2, 3]}
We can see that using the .copy()
method, we were able to modify the value in the new dictionary and have the old value remain the same. In the example above, we used f-strings to print out our dictionaries. This feature is available in Python 3.8 and higher. To learn more about f-strings, check out my tutorial here.
Let’s see what happens when we modify the list value in our copied dictionary:
# Modifying a non-primitive data type in a copied dictionary
original = {'a': 1, 'b': 2, 'c': [1,2,3]}
copied = original.copy()
copied['c'].append(99)
print(f'{original=}')
print(f'{copied=}')
# Returns:
# original={'a': 1, 'b': 2, 'c': [1, 2, 3, 99]}
# copied={'a': 1, 'b': 2, 'c': [1, 2, 3, 99]}
We can see that when we modified the value of a non-primitive data type (such as a list), the value in the original dictionary was also modified.
This is because when we used the .copy()
method to create a copy of the dictionary, we created a shallow copy. This meant that items were copied lazily, attempting to duplicate as little as possible.
In the next section, you’ll learn how to create a deep copy in order to ensure that these associative links are broken entirely.
How to Deep Copy a Python Dictionary
If we want to create a duplicate of a dictionary that breaks all links to the original, we can create a deep copy of the dictionary. In order to do this, we first need to import the copy
module, which comes with a function deepcopy()
.
Let’s see how we can use this function to create a deep duplicate of the dictionary:
# Creating a Deep Copy of a Dictionary in Python
from copy import deepcopy
original = {'a': [1,2,3], 'b': 2, 'c': [1, 2, 3]}
copied = deepcopy(original)
Now, let’s see what happens when we modify a non-primitive data type in our dictionary:
# Modifying a Non-Primitive Data Type in a Deep Copy
copied['c'].append(99)
print(f'{original=}')
print(f'{copied=}')
# Returns:
# original={'a': [1, 2, 3], 'b': 2, 'c': [1, 2, 3]}
# copied={'a': [1, 2, 3], 'b': 2, 'c': [1, 2, 3, 99]}
When we create a deep duplicate, we create an entirely new object that copies that dictionary at that point in time.
Conclusion
In this tutorial, you learned how to copy a Python dictionary. You learned the differences between creating a copy using the =
operator, the .copy()
method, and using the deepcopy()
function. You learned how shallow copies create lazy copies. Meanwhile, deep copies duplicate everything in the dictionary and break all the associative ties to the dictionary.
Additional Resources
To learn more about related topics, check out the tutorials below: