Python Dictionary copy()


Python dictionary copy() method

Python dictionary copy() method returns a shallow copy of the dictionary.

In this tutorial, you will learn about dictionary copy() method in Python, and its usage, with the help of example programs.

Syntax of dict copy()

The syntax of dictionary copy() method is

dictionary.copy()

Parameters

The dictionary copy() method takes no parameters.

Return value

The dictionary copy() method returns a dict type object.

Please note that the copy() method makes a shallow copy of the dictionary. A shallow copy means only the keys and the values are copied. If values are references to other objects like a list, user defined object, etc., then those references are copied instead of the actual data in them. Therefore, when you make any changes to the objects given by those references, then the copied dictionary is also affected.

Examples for copy() method

1. Copying the given dictionary in Python

In this example, we are given a dictionary in my_dict with some initial key:value pairs where the keys are strings and values are integers. We have to copy this dictionary.

We shall call copy() method on the given dictionary object my_dict, and store the returned value in my_dict_copy and print the copy to output.

Python Program

my_dict = {
    'foo': 12,
    'bar': 14
}

my_dict_copy = my_dict.copy()
print(my_dict_copy)

Output

{'foo': 12, 'bar': 14}

2. Shallow copying dictionary of lists Python

In this example, we are given a dictionary of lists in my_dict where the values are references to some predefined lists. We have to copy this dictionary.

We shall call copy() method on the given dictionary object my_dict, and store the returned value in my_dict_copy and print the copy to output.

Python Program

fruits_list = ['apple', 'banana', 'cherry']
colors_list = ['red', 'blue', 'green']

my_dict = {
    'fruits': fruits_list,
    'colors': colors_list
}

my_dict_copy = my_dict.copy()
print(my_dict_copy)

Output

{'fruits': ['apple', 'banana', 'cherry'], 'colors': ['red', 'blue', 'green']}

Perfectly copied. Right! No. After copying the dictionary, let us change one of the lists by adding a new item. Say, add a new item to the colors_list.

Python Program

fruits_list = ['apple', 'banana', 'cherry']
colors_list = ['red', 'blue', 'green']

my_dict = {
    'fruits': fruits_list,
    'colors': colors_list
}

my_dict_copy = my_dict.copy()

colors_list.append('yellow')

print(my_dict_copy)

Output

{'fruits': ['apple', 'banana', 'cherry'], 'colors': ['red', 'blue', 'green', 'yellow']}

Since we are using references to create the dictionary, which is then copied, and the data at the reference is changed, the copied dictionary is also affected.

Summary

In this tutorial of Python Dictionary Methods, we learned how to use Dictionary copy() method to make a shallow copy of a given dictionary, with help of well detailed Python programs.