The Wayback Machine - https://web.archive.org/web/20240927175024/https://www.geeksforgeeks.org/python-dictionary-copy/
Open In App

Python Dictionary copy()

Last Updated : 08 Jul, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python Dictionary copy() method returns a shallow copy of the dictionary. let’s see the Python Dictionary copy() method with examples:

 Examples

Input: original = {1:'geeks', 2:'for'}
        new = original.copy() // Operation
        
Output: original:  {1: 'one', 2: 'two'}
         new:  {1: 'one', 2: 'two'}

Syntax of copy() method

Syntax:  dict.copy() 

Return:  This method doesn’t modify the original, dictionary just returns copy of the dictionary.

Python Dictionary copy() Error: 

As we are not passing any parameters, there is no chance of any error.

Example 1: Examples of Python Dictionary copy()

Python program to demonstrate the working of dictionary copy.

Python3




original = {1: 'geeks', 2: 'for'}
 
# copying using copy() function
new = original.copy()
 
# removing all elements from the list
# Only new list becomes empty as copy()
# does shallow copy.
new.clear()
 
print('new: ', new)
print('original: ', original)


Output: 

new:  {}
original:  {1: 'geeks', 2: 'for'}

Example 2: Python Dictionary copy() and update

Python program to demonstrate the working of dictionary copy. i.e. Updating dict2 elements and checking the change in dict1.

Python3




# given dictionary
dict1 = {10: 'a', 20: [1, 2, 3], 30: 'c'}
print("Given Dictionary:", dict1)
 
# new dictionary and
# copying using copy() method
dict2 = dict1.copy()
print("New copy:", dict2)
 
# Updating dict2 elements and
# checking the change in dict1
dict2[10] = 10
dict2[20][2] = '45'  # list item updated
 
print("Updated copy:", dict2)


Output:

Given Dictionary: {10: 'a', 20: [1, 2, 3], 30: 'c'}
New copy: {10: 'a', 20: [1, 2, 3], 30: 'c'}
Updated copy: {10: 10, 20: [1, 2, '45'], 30: 'c'}

Difference between shallow copy and deep copy

It means that any changes made to a copy of the object do not reflect in the original object. In python, this is implemented using “deepcopy()” function. whereas in shallow copy any changes made to a copy of an object do reflect in the original object. In python, this is implemented using the “copy()” function.

Example 1: Using copy()

Unlike copy(), the assignment operator does deep copy. 

Python3




# Python program to demonstrate difference
# between = and copy()
original = {1: 'geeks', 2: 'for'}
 
# copying using copy() function
new = original.copy()
 
# removing all elements from new list
# and printing both
new.clear()
print('new: ', new)
print('original: ', original)
 
 
original = {1: 'one', 2: 'two'}
 
# copying using =
new = original
 
# removing all elements from new list
# and printing both
new.clear()
print('new: ', new)
print('original: ', original)


Output: 

new:  {}
original:  {1: 'geeks', 2: 'for'}
new:  {}
original:  {}

Example 2: Using copy.deepcopy

Unlike deepcopy(), the assignment operator does deep copy. 

Python3




import copy
 
# Python program to demonstrate difference
# between = and copy()
original = {1: 'geeks', 2: 'for'}
 
# copying using copy() function
new = copy.deepcopy(original)
 
# removing all elements from new list
# and printing both
new.clear()
print('new: ', new)
print('original: ', original)
 
original = {1: 'one', 2: 'two'}
 
# copying using =
new = original
 
# removing all elements from new list
# and printing both
new.clear()
print('new: ', new)
print('original: ', original)


Output: 

new:  {}
original:  {1: 'geeks', 2: 'for'}
new:  {}
original:  {}


Previous Article
Next Article

Similar Reads

copy in Python (Deep Copy and Shallow Copy)
In Python, Assignment statements do not copy objects, they create bindings between a target and an object. When we use the = operator, It only creates a new variable that shares the reference of the original object. In order to create "real copies" or "clones" of these objects, we can use the copy module in Python. Syntax of Python DeepcopySyntax:
7 min read
Difference Between Shallow copy VS Deep copy in Pandas Dataframes
The pandas library has mainly two data structures DataFrames and Series. These data structures are internally represented with index arrays, which label the data, and data arrays, which contain the actual data. Now, when we try to copy these data structures (DataFrames and Series) we essentially copy the object's indices and data and there are two
4 min read
Shallow copy vs Deep copy in Pandas Series
The pandas library has mainly two data structures DataFrames and Series. These data structures are internally represented with index arrays, which label the data, and data arrays, which contain the actual data. Now, when we try to copy these data structures (DataFrames and Series) we essentially copy the object's indices and data and there are two
4 min read
NumPy ndarray.copy() Method | Make Copy of a Array
The ndarray.copy() method returns a copy of the array. It is used to create a new array that is a copy of an existing array but does not share memory with it. This means that making any changes to the original array won't affect the existing array. Example C/C++ Code # Python program explaining # numpy.ndarray.copy() function import numpy as geek x
2 min read
Python | Ways to Copy Dictionary
Dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. It is widely used in day to day programming, web development, and machine learning. When we simply assign dict1 = dict2 it refers to the same dictionary. Let's discuss a few ways to copy the
3 min read
Python | Pretty Print a dictionary with dictionary value
This article provides a quick way to pretty How to Print Dictionary in Python that has a dictionary as values. This is required many times nowadays with the advent of NoSQL databases. Let's code a way to perform this particular task in Python. Example Input:{'gfg': {'remark': 'good', 'rate': 5}, 'cs': {'rate': 3}} Output: gfg: remark: good rate: 5
7 min read
set copy() in python
The copy() method returns a shallow copy of the set in python. If we use "=" to copy a set to another set, when we modify in the copied set, the changes are also reflected in the original set. So we have to create a shallow copy of the set such that when we modify something in the copied set, changes are not reflected back in the original set. Synt
2 min read
Python | Difference between Pandas.copy() and copying through variables
Pandas .copy() method is used to create a copy of a Pandas object. Variables are also used to generate copy of an object but variables are just pointer to an object and any change in new data will also change the previous data. The following examples will show the difference between copying through variables and Pandas.copy() method. Example #1: Co
2 min read
Python | Pandas Index.copy()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.copy() function make a copy of this object. The function also sets the name and dtype attribute of the new object as that o
2 min read
Python | Pandas TimedeltaIndex.copy
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas TimedeltaIndex.copy() function make a copy of this TimedeltaIndex object. The function also sets the Name and dtype attributes on
2 min read
Python | Numpy matrix.copy()
With the help of Numpy matrix.copy() method, we can make a copy of all the data elements that is present in matrix. If we change any data element in the copy, it will not affect the original matrix. Syntax : matrix.copy() Return : Return copy of matrix Example #1 : In this example we can see that with the help of matrix.copy() method we are making
1 min read
Python | Pandas tseries.offsets.DateOffset.copy
Dateoffsets are a standard kind of date increment used for a date range in Pandas. It works exactly like relativedelta in terms of the keyword args we pass in. DateOffsets work as follows, each offset specify a set of dates that conform to the DateOffset. For example, Bday defines this set to be the set of dates that are weekdays (M-F). DateOffsets
3 min read
Python | Pandas tseries.offsets.BusinessDay.copy
Dateoffsets are a standard kind of date increment used for a date range in Pandas. It works exactly like relativedelta in terms of the keyword args we pass in. DateOffsets work as follows, each offset specify a set of dates that conform to the DateOffset. For example, Bday defines this set to be the set of dates that are weekdays (M-F). DateOffsets
3 min read
Python | Pandas tseries.offsets.BusinessHour.copy
Dateoffsets are a standard kind of date increment used for a date range in Pandas. It works exactly like relativedelta in terms of the keyword args we pass in. DateOffsets work as follows, each offset specify a set of dates that conform to the DateOffset. For example, Bday defines this set to be the set of dates that are weekdays (M-F). DateOffsets
3 min read
Python | Pandas tseries.offsets.CustomBusinessDay.copy
Dateoffsets are a standard kind of date increment used for a date range in Pandas. It works exactly like relativedelta in terms of the keyword args we pass in. DateOffsets work as follows, each offset specify a set of dates that conform to the DateOffset. For example, Bday defines this set to be the set of dates that are weekdays (M-F). DateOffsets
3 min read
Python | Pandas tseries.offsets.CustomBusinessHour.copy
Dateoffsets are a standard kind of date increment used for a date range in Pandas. It works exactly like relativedelta in terms of the keyword args we pass in. DateOffsets work as follows, each offset specify a set of dates that conform to the DateOffset. For example, Bday defines this set to be the set of dates that are weekdays (M-F). DateOffsets
3 min read
Python | shutil.copy() method
C/C++ Code # Python program to explain shutil.copy() method # importing shutil module import shutil # Source path source = "/home/User/Documents/file.txt" # Destination path destination = "/home/User/Documents/file.txt" # Copy the content of # source to destination try: shutil.copy(source, destination) print("File copied su
5 min read
Python | Move or Copy Files and Directories
Let's say we want to copy or move files and directories around, but don’t want to do it by calling out to shell commands. The shutil module has portable implementations of functions for copying files and directories. Code #1 : Using shutil module import shutil # Copy src to dst. (cp src dst) shutil.copy(src, dst) # Copy files, but preserve metadata
3 min read
Python PIL | copy() method
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. PIL.Image.copy() method copies the image to another image object, this method is useful when we need to copy the image but also retain the original. Syntax:Image.copy() Parameters: no arguments Returns:An image object # Importing Image module fr
1 min read
Python | How to copy data from one excel sheet to another
In this article, we will learn how to copy data from one excel sheet to destination excel workbook using openpyxl module in Python. For working with excel files, we require openpyxl, which is a Python library that is used for reading, writing and modifying excel (with extension xlsx/xlsm/xltx/xltm) files. It can be installed using the following com
3 min read
Copy a directory recursively using Python (with examples)
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories.shutil.copytree() method recursively copies an entire directory tree rooted at source (src) to the desti
5 min read
Create Copy-Move GUI using Tkinter in Python
Everyone reading this post is well aware of the importance of Copying the file or moving the file from one specific location to another. In this post, we have tried to explain not only the program but added some exciting pieces of Interface. Up to now, many of you may get about what we are talking about. Yes, you are right, We are going to use "Tki
4 min read
How to Copy a Table in MySQL Using Python?
In this article, we will create a table in MySQL and will create a copy of that table using Python. We will copy the entire table, including all the columns and the definition of the columns, as well as all rows of data in the table. To connect to MySQL database using python, we need PyMySql module. The cursor class allows python to execute SQL com
3 min read
Python Pandas - DataFrame.copy() function
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. There are many ways to copy DataFrame in pandas. The first way is a simple way of assigning a dataframe object to a variable, but this h
2 min read
How to Copy a Table Definition in MySQL Using Python?
Python requires an interface to access a database server. Python supports a wide range of interfaces to interact with various databases. To communicate with a MySQL database, MySQL Connector Python module, an API written purely in Python, is used. This module is self-sufficient meaning that it does not have dependencies and only requires the standa
6 min read
Python - Copy Files From Subfolders to the Main folder
In this article, we will discuss how to copy a file from the subfolder to the main folder. The directory tree that will be used for explanation in this article is as shown below: D:\projects\base | |__subfolder: | \__file.txt | |__main.py | Here we have a folder named "base" in which we have a folder named "subfolder" which contains a file name fil
4 min read
Python - Copy Directory Structure Without Files
In this article, we will discuss how to copy the directory structure with files using Python. For example, consider this directory tree: We have a folder named "base" and inside have we have one folder named "Structure". "Structure" has some folders inside which also contain some files. Now we have to copy all the folders of "Structure" to a folder
3 min read
Python - Copy all the content of one file to another file in uppercase
In this article, we are going to write a Python program to copy all the content of one file to another file in uppercase. In order to solve this problem, let's see the definition of some important functions which will be used: open() - It is used to open a file in various modes like reading, write, append, both read and write.write() - It is used t
2 min read
Copy And Replace Files in Python
In Python, copying and replacing files is a common task facilitated by modules like `shutil` and `os`. This process involves copying a source file to a destination location while potentially replacing any existing file with the same name. Leveraging functions like `shutil.copy2` and `os.remove`, this operation is crucial for updating or maintaining
2 min read
Copy Constructor in Python
In object-oriented programming, a copy constructor is a special type of constructor that creates a new object as a copy of an existing object. It is a crucial concept in many programming languages, including Python. Python, being an object-oriented language, supports the implementation of copy constructors to enable the creation of new objects by c
3 min read
Article Tags :
Practice Tags :