AppDividend
Latest Code Tutorials

Python Dictionary Copy Example | copy() Method Tutorial

0 13

Get real time updates directly on you device, subscribe now.

Python Dictionary Copy Example | copy() Method Tutorial is today’s topic.

Dictionary is a famous data structure in Python. 

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

It returns a shallow copy of the dictionary. 

The copy() method doesn’t take any parameters. It doesn’t modify the original dictionary.

Python Dictionary Copy Example

The syntax of copy() method in Python Dictionary is following.

dictionary.copy()

See the following example.

# app.py

appDict = { 
    'shopping': 'flipkart',
    'transport': 'ola',
    'banking': 'paytm',
    'hotel': 'oyo rooms'
 }
secDict = appDict.copy()
print(secDict)

See the below output.

Python Dictionary Copy Example | copy() Method Tutorial

 

In the above example, an exact copy of appDict is created and assigned to the secDict.

Difference between copy() Method and = Operator

When copy() method is used, a new dictionary is created which is filled with a copy of the references from an original dictionary.

When the = operator is used, a new reference to an original dictionary is created.

Let us take the example of the = operator.

# app.py

origDict = { 
    'shopping': 'flipkart',
    'transport': 'ola',
    'banking': 'paytm',
    'hotel': 'oyo rooms'
 }
copyDict = origDict
print(copyDict)

See the output below.

 

Difference between copy() Method and = Operator

Let’s see another example.

# app.py

origDict = { 
    'shopping': 'flipkart',
    'transport': 'ola',
    'banking': 'paytm',
    'hotel': 'oyo rooms'
 }
copyDict = origDict.copy()
print(copyDict)

origDict.clear()
print(copyDict)

Here, first, we are creating a copy of the Dictionary and then clear the original dictionary and see if the copied dictionary emptied or not. The output is following.

 

copy() Method Tutorial

Now, use the = operator and see the output.

# app.py

origDict = { 
    'shopping': 'flipkart',
    'transport': 'ola',
    'banking': 'paytm',
    'hotel': 'oyo rooms'
 }
copyDict = origDict
print(copyDict)

origDict.clear()
print(copyDict)

Here, when we clear the original dictionary, the copied dictionary also cleared as well. So that is the main big difference between copy() and = operator.

Finally, Python Dictionary Copy Example | copy() Method Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.