How to Copy a Dictionary in Python

Created
Modified

Using dict Method

If you want to copy the dict, you have to do so explicitly with:

#!/usr/bin/python3

a = {"a": 1, "b": 2}
# Copy
b = dict(a)
b['a'] = 3
print(a)
print(b)
{'a': 1, 'b': 2}
{'a': 3, 'b': 2}

Using dict.copy Method

The copy() method returns a copy of the dictionary.

#!/usr/bin/python3

a = {"a": 1, "b": 2}
# Copy
b = a.copy()
print(b)
{'a': 1, 'b': 2}

Using copy Module

The copy.deepcopy() method returns a deep copy of x.

#!/usr/bin/python3

# Import module
import copy

a = {"a": 1, "b": 2}
# Copy
b = copy.deepcopy(a)
print(b)
{'a': 1, 'b': 2}

Using ** Unpackaging Operator

On python 3.5+ there is an easier way to achieve a shallow copy by using the ** unpackaging operator. Defined by Pep 448.

#!/usr/bin/python3

a = {"a": 1, "b": 2}
# Copy
b = {**a}
print(b)
{'a': 1, 'b': 2}

Related Tags