Post

Python Dictionary copy()

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

Python Dictionary copy()

The syntax of copy() is:

1
2
dictionary.copy()

copy() Parameters

The copy() method does not take any parameters as arguments.

Example 1: How to use copy() method in python dictionary?

1
2
3
4
5
6
7
8
cars = {1 : "TATA",2 : "BMW", 3 : "TOYOTA"}
print("First Dictionary is:",cars)

# coping dictionary using copy() method
new_cars = cars.copy()

print("Second Dictionary is:",new_cars)

Output:

1
2
3
First Dictionary is: {1: 'TATA', 2: 'BMW', 3: 'TOYOTA'}
Second Dictionary is: {1: 'TATA', 2: 'BMW', 3: 'TOYOTA'}

Note: The copy() method is entirely different from = operator, as = operator is used for creating a new reference to the original dictionary and copy() method is used to create a new dictionary from the reference from the original dictionary that is filled with the same items as the original dictionary.

Example 2: How = operator is different from copy() method in python dictionaries?

1
2
3
4
5
6
7
8
9
10
11
cars = {1 : "TATA",2 : "BMW", 3 : "TOYOTA"}
print("First Dictionary is:",cars)

new_cars = cars

# clearing dictionary using clear() method
new_cars.clear()

print("First Dictionary is:",cars)
print("Second Dictionary is:",new_cars)

Output:

1
2
3
4
First Dictionary is: {1: 'TATA', 2: 'BMW', 3: 'TOYOTA'}
First Dictionary is: {}
Second Dictionary is: {}

Here, when the new_cars dictionary is cleared, the cars dictionary is also cleared.

Rules of copy()

  • Given object must be a dictionary, else returns an AttributeError exception.
This post is licensed under CC BY 4.0 by the author.