In this Python tutorial, we will see how to copy a dictionary in Python using some examples. We will see some methods to copy a dictionary in Python.
A dictionary in Python can store many key-value pairs in a place. Copying the data manually can be time-consuming.
Sometimes, we make some changes in the original data but, after some time, we need previous data to be restored(that cannot be retained back). So, we should not change the original data, until we are sure. Here, comes the use of copy a dictionary in Python.
For example, there is a tech company having four different departments in it. They store the number of employees working in different departments in the form of a Python dictionary every year. What they do is, take last year’s data and make a copy of it, and then update the copied one with the updation required. and store it as the
employee_2022 = {
'Networking': 5,
'Cyber security': 10,
'Developer': 12,
'Administration': 8
}
print('Numbers of employees working in 2022: \n', employee_2022)
employee_2023 = dict(employee_2022)
print('Numbers of employees working in 2023: \n', employee_2023)
employee_2023['Developer']: 14
print('updated employee data in 2023: \n', employee_2023)
As the output of this code:
Numbers of employees working in 2022:
{'Networking': 5, 'Cyber security': 10, 'Developer': 12, 'Administration': 8}
Numbers of employees working in 2023:
{'Networking': 5, 'Cyber security': 10, 'Developer': 12, 'Administration': 8}
updated employee data in 2023:
{'Networking': 5, 'Cyber security': 10, 'Developer': 14, 'Administration': 8}
Previous year(2022) employee data:
{'Networking': 5, 'Cyber security': 10, 'Developer': 12, 'Administration': 8}
we can easily see that no change occurred in last year’s stored data in the Python dictionary. And we easily updated the data to be the new year data by copy a dictionary in Python. And now, we have both years’ data.
Copy a dictionary in Python
There are six different methods to copy a Python dictionary. They are:
- Using dict() constructor
- Using the dictionary comprehension method
- Using for loop
- Using copy()
- Using deepcopy() from copy module
- Using = (Assignment) Operator
Let’s see them one by one.
Method 1: Coping a Python dictionary using the dict() constructor
As we know, the dict() constructor is used to create a dictionary in Python. Here, we will just give the original dictionary as an argument to the dict() constructor and will store the value in the copied dictionary.
In the following example: we have a detail of an e-commerce inventory. Where the ID of the products are keys and the quantities available in inventory are values.
Product_data = {
'004592': 36,
'004593': 58,
'004516': 20,
'004603': 17
}
print('The original inventory data are: \n', Product_data)
Copied_product_data = dict(Product_data)
print('The inventory data that gonna be copied is: \n', Copied_product_data)
The output is:
The original inventory data are:
{'004592': 36, '004593': 58, '004516': 20, '004603': 17}
The inventory data that gonna be copied is:
{'004592': 36, '004593': 58, '004516': 20, '004603': 17}
This way we can easily use dict() function in Python to copy a Python dictionary.
Method 2: Python copy dict using the dictionary comprehension
In this method, we will be using dictionary comprehension to craft a copied dictionary using the items of the original dictionary.
In this example: we have a company, that had assigned some projects to their employees in groups. By the time they can change the projects assigned to the employees.
Project_assigned = {
'salesforce': ['Samy', 'abby'],
'SAP': ['dave', 'david'],
'Python': ['Veronica', 'joey']
}
print('Assigned project names: \n', Project_assigned)
Working_project = {key: value for key, value
in Project_assigned.items()}
print('Working project names: \n', Working_project)
The output of the Python code:
Assigned project names:
{'salesforce': ['Samy', 'abby'], 'SAP': ['dave', 'david'], 'Python': ['Veronica', 'joey']}
Working project names:
{'salesforce': ['Samy', 'abby'], 'SAP': ['dave', 'david'], 'Python': ['Veronica', 'joey']}
The company has successfully copied the data using dictionary comprehension for copy a dictionary in Python.
Method 3: Python copy dictionary using for loop
For loop in Python is used to loop over a sequence. Here, we will loop over the original dictionary using a for loop, and we will save all the copied elements in the copied dictionary.
In the example: We have details of racers’ in the USA in 2023 with racers’ names and the records held by them. By the time these records can change.
Racers = {
'Lex Hilton': '3:58.70i*',
'Jake Gebhardt': '3:59.18i*',
'Camden Marshall': '3:59.30i'
}
print('The top racers are: \n', Racers)
Copy_racers_data = {}
for key, value in Racers.items():
Copy_racers_data[key] = value
print('the copies data : \n', Copy_racers_data)
The Output of this code:
The top racers are:
{'Lex Hilton': '3:58.70i*', 'Jake Gebhardt': '3:59.18i*', 'Camden Marshall': '3:59.30i'}
the copies data :
{'Lex Hilton': '3:58.70i*', 'Jake Gebhardt': '3:59.18i*', 'Camden Marshall': '3:59.30i'}
This way we can use for loop to copy a dictionary in Python.
Method 4: Python dict assignment copy or reference using copy() method
The copy() method in Python creates a shallow copy of a dictionary. The copy() function takes no arguments. Here, we will use the copy() method to copy the elements from the original dictionary to another dictionary.
In the example, we have data from a library, and there is the name of the book issued and the person to whom the book has been issued.
Library_books_week01 = {
'Invisible Man': 'Amy',
'Beloved': 'Cabby',
'To Kill a Mockingbird': 'Ian'
}
print('Library books assigned: \n', Library_books_week01)
week02 = Library_books_week01.copy()
print('copied data from library:\n', week02)
The output is:
Library books assigned:
{'Invisible Man': 'Amy', 'Beloved': 'Cabby', 'To Kill a Mockingbird': 'Ian'}
copied data from library:
{'Invisible Man': 'Amy', 'Beloved': 'Cabby', 'To Kill a Mockingbird': 'Ian'}
Method 5: Python dictionary deep copy from copy module
The deepcopy() method in Python is a member of the copy module. It returns a new dictionary with copied elements of the passed dictionary. It copies, all the elements of the given dictionary in a recursive manner.
In the given example, we have taken the data from a cycle race. the racers have been assigned their track number. But, after the race starts the cyclist can change their track if required. So, to keep the records we need to change the data as per required.
import copy
cycle_race = {
'rake': 5,
'dave': 1,
'gia': 2
}
print('cyclist name with their track number: \n', cycle_race)
after_1_hour = copy.deepcopy(cycle_race)
print('cyclist after 1 hour:\n', after_1_hour)
The output of this block of code:
Library books assigned:
{'Invisible Man': 'Amy', 'Beloved': 'Cabby', 'To Kill a Mockingbird': 'Ian'}
copied data from library:
{'Invisible Man': 'Amy', 'Beloved': 'Cabby', 'To Kill a Mockingbird': 'Ian'}
This way, we can use deepcopy() from copy module to copy a Python dictionary.
Method 6: Python copy dictionary without reference using =(Assignment Operator )
Assignment Operators are used for assigning values to variables irrespective of the type or class of the value, as Python is a dynamically typed Programming language.
Until now, we saw the methods when we were changing or updating the data in the copied dictionary, and nothing happened to the original dictionary. But, In this method, if we change/update the copied dictionary data, automatically, the data will change in the original/parent dictionary.
To have a backup dictionary for any dictionary, we should use this method of copying a Python dictionary.
In this example, we will just use the = operator and will assign the original dictionary to a variable. Here, we have assigned the household work to the people. we will see how to copy this data and we will also see what happens to the original/parent Python dictionary when we change the data of the copied dictionary.
work_assigned = {
'Dusting': ['Samy', 'Abby'],
'Cooking': ['Dave', 'David'],
'Gardening': ['Veronica', 'Joey']
}
print('work assigned: \n', work_assigned)
work_going = work_assigned
print('Work going on: \n', work_going)
work_going['washing'] = ['Ian', 'Ray']
print('Updated work going on: \n', work_going)
print('Parent dictionary: \n', work_assigned)
The output of this block of code:
work assigned:
{'Dusting': ['Samy', 'Abby'], 'Cooking': ['Dave', 'David'], 'Gardening': ['Veronica', 'Joey']}
Work going on:
{'Dusting': ['Samy', 'Abby'], 'Cooking': ['Dave', 'David'], 'Gardening': ['Veronica', 'Joey']}
Updated work going on:
{'Dusting': ['Samy', 'Abby'], 'Cooking': ['Dave', 'David'], 'Gardening': ['Veronica', 'Joey'], 'washing': ['Ian', 'Ray']}
Parent dictionary:
{'Dusting': ['Samy', 'Abby'], 'Cooking': ['Dave', 'David'], 'Gardening': ['Veronica', 'Joey'], 'washing': ['Ian', 'Ray']}
This way, we can use the = operator to copy the dictionary in Python.
Conclusion:
This tutorial has seen many methods to copy a Python dictionary. If we want an actual copy, then we must want the copy not to affect the original dictionary, but if we want a copied dictionary to change should be backup data for the parent dictionary, kindly use the = operator
function.
You may also like to read:
- copy specific keys in Python Dictionary
- update duplicate keys in Python Dictionary
- Remove duplicate values from a Python Dictionary
- Copy a Python dictionary without some of its keys?
Find A Teacher Form:
https://docs.google.com/forms/d/1vREBnX5n262umf4wU5U2pyTwvk9O-JrAgblA-wH9GFQ/viewform?edit_requested=true#responses
Email:
public1989two@gmail.com
www.itsec.hk
www.itsec.vip
www.itseceu.uk
Leave a Reply