Skip to content
Home » Dictionary Methods – copy

Dictionary Methods – copy

Spread the love

In my previous articles we discussed the following dictionary methods:

pop and popitem

get

setdefault

fromkeys

Feel free to read about them if you haven’t done so yet.

In this article we’ll be talking about the dictionary method copy.

Here’s the video version of this article:

We use the copy method to copy a dictionary:

 >>> rooms = {"Steven" : 42, "Natalie" : 12, "Peter" : 112, "Francis" : 14}
 >>> rooms_copy = rooms.copy()
 >>> print(rooms)
 {'Steven': 42, 'Natalie': 12, 'Peter': 112, 'Francis': 14}
  
 >>> print(rooms_copy)
 {'Steven': 42, 'Natalie': 12, 'Peter': 112, 'Francis': 14}
  
 >>> rooms_copy["Peter"] = 115 

The change is now visible in the copy where it was made, but not in the original:

 >>> rooms
 {'Steven': 42, 'Natalie': 12, 'Peter': 112, 'Francis': 14}
  
 >>> rooms_copy
 {'Steven': 42, 'Natalie': 12, 'Peter': 115, 'Francis': 14} 

What we get using the copy method is a shallow copy. If you want to learn more about the difference between shallow copies and deep copies, you can read these two articles:

Copying Lists – Shallow Copies

Copying Lists – Deep Copies

They are about lists, and, as you know, lists can be used as values in a dictionary.

So, if a value in the dictionary is a complex data type (like a list), only the reference will be copied:

 >>> results = {"Anne" : 5, "George" : [4,6]}
 >>> results_copy = results.copy() 

Just checking if the copy method worked. It did:

 >>> results
 {'Anne': 5, 'George': [4, 6]}
  
 >>> results_copy
 {'Anne': 5, 'George': [4, 6]} 

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Let’s change the second element in the list in the copy:

 >>> results_copy["George"][1] = 7 

The change is now visible in both the original and the copy:

 >>> results
 {'Anne': 5, 'George': [4, 7]}
  
 >>> results_copy
 {'Anne': 5, 'George': [4, 7]} 

Now let’s change the whole list:

 >>> results_copy["George"] = [3,8] 

This time the change is visible only in the copy.

 >>> results
 {'Anne': 5, 'George': [4, 7]}
  
 >>> results_copy
 {'Anne': 5, 'George': [3, 8]} 

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love
Tags:

Leave a Reply