Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy a dictionary into a new variable without maintaining the link with previous one

I want to copy a dictionary into a new variable without maintaining the link with previous variable.

like image 889
Manoj Suryawanshi Avatar asked Jan 07 '12 18:01

Manoj Suryawanshi


1 Answers

from copy import deepcopy

new_dict = deepcopy(orig_dict)

dict.copy() creates shallow copies, which means, if your dictionary contains other container-objects like list, tuples, etc. they will be referenced again and not duplicated!

You can try for yourself with:

a = {1:{1:2}}
print id(a[1])
>>> 159584844

b = a.copy()
print id(b[1])
>>> 159584844

c = deepcopy(a)
print id(c[1])
>>> 159575276
like image 179
Don Question Avatar answered Oct 02 '22 17:10

Don Question