Create a duplicate for dictionary in Python

Create a new dictionary from key value pair

The copy method returns a new dictionary with the same key and value pair from the existing dictionary.

Pay more attention to this method as copy method only does the shallow copy, which means that the values are the same.


x = {'username': 'admin', 'machines': ['foo', 'bar', 'baz']} 
y = x.copy() # from  w  ww .j  a v  a 2s .  co  m
y['username'] = 'mlh' 
y['machines'].remove('bar') 
print y 
print x 

The code above generates the following result.

To make a deep copy, copying the values, any values they contain, and so forth as well. You accomplish this using the function deepcopy from the copy module:

The following code shows how to do deep copy.


from copy import deepcopy 
d = {} # from  w w  w  .  java2 s. co m
d['names'] = ['java2s'] 
c = d.copy() 
dc = deepcopy(d) 
d['names'].append('Python')
print c 
print dc 

The code above generates the following result.

Shallow copy

copy method returns a duplicate shallow dictionary.


x = {'username': 'admin', 'machines': ['foo', 'bar', 'baz']}
y = x.copy()# www .  j  a v  a 2  s  . c  o  m

y['username'] = 'mlh'
y['machines'].remove('bar')
print y
print x

The code above generates the following result.

Dictionary deep copy

There is a method called deepcopy from copy module which can do deep copy for dictionary.


from copy import deepcopy
d = {}#  ww w. ja  v a 2  s.  c  om
d['names'] = ['Alfred', 'Bertrand']
c = d.copy()
dc = deepcopy(d)
d['names'].append('Clive')
print c
print dc

The code above generates the following result.





















Home »
  Python »
    Data Types »




Data Types
String
String Format
Tuple
List
Set
Dictionary