Python Dictionary copy()

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}

Syntax of Dictionary copy()

The syntax of copy() is:

dict.copy()

copy() Arguments

The copy() method doesn't take any arguments.


copy() Return Value

This method returns a shallow copy of the dictionary. It doesn't modify the original dictionary.


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'}

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.


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.


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.


Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges