+

Python | Ways to copy a dictionary

Method # 1: Using copy()
The copy () method returns shallow copy of the dictionary. 
It takes no parameters and returns a new dictionary that does not reference the original dictionary.

# Python3 demo code
# how to copy the dictionary
# using the copy () function

 

 
# initializing dictionary

test1 = { " name " : " akshat " , "name1" : "manjeet" , " name2 " : " vashu " }

  

 
# method for copying the dictionary using the copy () function

test2 = test1.copy ()

 

 
# test2 update

test2 [ "name1" ] = "nikhil"

 
# print starter dictionary

print ( "initial dictionary =" , test1)

  
# printing the updated dictionary

print ( "updated dictionary =" , test2)

Exit

 initial dictionary = {`name1`:` manjeet`, `name2`:` vashu`, `name `:` akshat`} updated dictionary = {`name1`:` nikhil`, `name`:` akshat`, `name2`:` vashu`} 

Method # 2: Using dict ()
dict () — it is a constructor that creates a dictionary in Python.

# Python3 demo code
# as copy dictionary
# using dict ()

 

 
# initializing dictionary

test1 = { "name" : "akshat" , "name1" : "manjeet" , " name2 " : " vashu " }

  

 
# method to copy the dictionary using dict

test2 = dict (test1)

 

 
# test2 update

test2 [ " name1 " ] = " nikhil "

 
# print the initial dictionary

print ( "initial dictionary =" , test1 )

 
# print updated dictionary

print ( "updated dictionary =" , test2)

Exit

 initial dictionary = {`name2`:` vashu`, `name`:` akshat`, `name1`:` manjeet`} updated dictionary = {`name2 `:` vashu`, `name`:` akshat`, `name1`:` nikhil`} 

Method # 3: Using Dictionary Comprehension

# Python3 demo code
# how to copy the dictionary
# using dictionary understanding

  

  
# initializing dictionary

test1 =   { "name" : " akshat " , " name1 " : "manjeet" , "name2" : "vashu" }

  

 
# method of copying a dictionary using dictionary comprehension

test2 = {k: v for k, v in test1.items ()}

 

 
# update test2

test2 [ "name1" ] = "ayush"

 
# print the initial dictionary

print ( "initial dictionary =" , test1)

 
# print the updated dictionary

print ( " updated dictionary = " , test2)

Exit

 initial dictionary = {`name`:` akshat`, `name2`:` vashu`, `name1`:` manjeet`} updated dictionary = {`name`:` akshat`, `name2`:` vashu`, `name1`:` ayush`} 
Get Solution for free from DataCamp guru