Table of Contents
In this tutorial, we will learn about the Python dictionary copy() method with the help of examples.
They copy()
method returns a copy (shallow copy) of the dictionary.
Example
original_marks = {'Physics':67, 'Maths':87} copied_marks = original_marks.copy() print('Original Marks:', original_marks) print('Copied Marks:', copied_marks) # Output: Original Marks: {'Physics': 67, 'Maths': 87} # Copied Marks: {'Physics': 67, 'Maths': 87}
1. Syntax of Dictionary copy()
The syntax of copy()
is:
dict.copy()
2. copy() Arguments
The copy()
method doesn’t take any arguments.
3. copy() Return Value
This method returns a shallow copy of the dictionary. It doesn’t modify the original dictionary.
4. Example 1: How copy works for dictionaries?
original = {1:'one', 2:'two'} new = original.copy() print('Orignal: ', original) print('New: ', new)
Output
Orignal: {1: 'one', 2: 'two'} New: {1: 'one', 2: 'two'}
5. Dictionary copy() Method Vs = Operator
When the copy()
method is used, a new dictionary is created which is filled with a copy of the references from the original dictionary.
When the =
operator is used, a new reference to the original dictionary is created.
6. Example 2: Using = Operator to Copy Dictionaries
original = {1:'one', 2:'two'} new = original # removing all elements from the list new.clear() print('new: ', new) print('original: ', original)
Output
new: {} original: {}
Here, when the new dictionary is cleared, the original dictionary is also cleared.
7. Example 3: Using copy() to Copy Dictionaries
original = {1:'one', 2:'two'} new = original.copy() # removing all elements from the list new.clear() print('new: ', new) print('original: ', original)
Output
new: {} original: {1: 'one', 2: 'two'}
Here, when the new dictionary is cleared, the original dictionary remains unchanged.