Python - Copy Dictionaries

Hello there, aspiring Python programmers! Today, we're going to dive into the fascinating world of dictionary copying in Python. As your friendly neighborhood computer science teacher, I'm excited to guide you through this journey. Let's imagine dictionaries as magical recipe books that we can duplicate. Sounds fun, right? Let's get started!

Python - Copy Dictionaries

Copy Dictionaries

In Python, dictionaries are incredibly useful data structures that store key-value pairs. But what if we want to create a copy of a dictionary? Well, that's where the magic begins!

Why Copy Dictionaries?

Before we jump into the 'how', let's understand the 'why'. Imagine you have a favorite cookie recipe (our dictionary), and you want to share it with a friend. You could give them your original recipe book, but what if they decide to add chili powder to the chocolate chip cookies? Yikes! That's why we make copies - to keep our original safe while allowing modifications to the copy.

Now, let's look at the different ways to copy dictionaries in Python.

Shallow Copy

A shallow copy creates a new dictionary, but the values are references to the original dictionary's values. It's like making a photocopy of your recipe book's table of contents - you have a new book, but it still points to the original recipes.

Let's see this in action:

original_dict = {"apple": 1, "banana": 2, "cherry": [3, 4, 5]}
shallow_copy = original_dict.copy()

print("Original dictionary:", original_dict)
print("Shallow copy:", shallow_copy)

# Modifying the shallow copy
shallow_copy["apple"] = 10
shallow_copy["cherry"][0] = 30

print("\nAfter modification:")
print("Original dictionary:", original_dict)
print("Shallow copy:", shallow_copy)

Output:

Original dictionary: {'apple': 1, 'banana': 2, 'cherry': [3, 4, 5]}
Shallow copy: {'apple': 1, 'banana': 2, 'cherry': [3, 4, 5]}

After modification:
Original dictionary: {'apple': 1, 'banana': 2, 'cherry': [30, 4, 5]}
Shallow copy: {'apple': 10, 'banana': 2, 'cherry': [30, 4, 5]}

Notice how changing the 'apple' value only affected the shallow copy, but modifying the 'cherry' list changed both dictionaries. This is because the list is mutable, and both dictionaries reference the same list object.

Deep Copy

A deep copy creates a new dictionary with new copies of the values. It's like rewriting the entire recipe book by hand - everything is brand new and independent.

To create a deep copy, we need to import the copy module:

import copy

original_dict = {"apple": 1, "banana": 2, "cherry": [3, 4, 5]}
deep_copy = copy.deepcopy(original_dict)

print("Original dictionary:", original_dict)
print("Deep copy:", deep_copy)

# Modifying the deep copy
deep_copy["apple"] = 10
deep_copy["cherry"][0] = 30

print("\nAfter modification:")
print("Original dictionary:", original_dict)
print("Deep copy:", deep_copy)

Output:

Original dictionary: {'apple': 1, 'banana': 2, 'cherry': [3, 4, 5]}
Deep copy: {'apple': 1, 'banana': 2, 'cherry': [3, 4, 5]}

After modification:
Original dictionary: {'apple': 1, 'banana': 2, 'cherry': [3, 4, 5]}
Deep copy: {'apple': 10, 'banana': 2, 'cherry': [30, 4, 5]}

See the difference? With a deep copy, modifying the 'cherry' list in the copy doesn't affect the original dictionary.

Copy Dictionaries Using copy() Method

The copy() method is a built-in dictionary method that creates a shallow copy. It's like the photocopy machine we mentioned earlier - quick and easy, but with the same limitations as a shallow copy.

Here's how to use it:

original_dict = {"apple": 1, "banana": 2, "cherry": [3, 4, 5]}
copy_dict = original_dict.copy()

print("Original dictionary:", original_dict)
print("Copied dictionary:", copy_dict)

# Modifying the copy
copy_dict["apple"] = 10
copy_dict["cherry"][0] = 30

print("\nAfter modification:")
print("Original dictionary:", original_dict)
print("Copied dictionary:", copy_dict)

Output:

Original dictionary: {'apple': 1, 'banana': 2, 'cherry': [3, 4, 5]}
Copied dictionary: {'apple': 1, 'banana': 2, 'cherry': [3, 4, 5]}

After modification:
Original dictionary: {'apple': 1, 'banana': 2, 'cherry': [30, 4, 5]}
Copied dictionary: {'apple': 10, 'banana': 2, 'cherry': [30, 4, 5]}

As you can see, the behavior is the same as our first shallow copy example.

Comparison of Dictionary Copying Methods

Let's summarize the different methods in a handy table:

Method Type of Copy Syntax Nested Objects
Assignment (=) Reference new_dict = original_dict Shared
copy() Shallow new_dict = original_dict.copy() Shared
dict() Shallow new_dict = dict(original_dict) Shared
deepcopy() Deep new_dict = copy.deepcopy(original_dict) Independent

Remember, choosing the right copying method depends on your specific needs. If you're working with simple dictionaries, a shallow copy might be sufficient. But if you're dealing with nested structures and need complete independence, go for a deep copy.

In conclusion, copying dictionaries in Python is like making copies of your favorite recipes. Sometimes you just need a quick reference (shallow copy), and other times you want to create a completely new cookbook (deep copy). The choice is yours, young Pythonista!

Now, why don't you try these methods out yourself? Create your own dictionary "recipe book" and experiment with different copying techniques. Happy coding, and may your dictionaries always be perfectly copied!

Credits: Image by storyset