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.

1

4 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 
3

The .copy method on the dictionary should suffice.

dict1 = {'foo': 'bar'} dict2 = dict1.copy() dict1['bar'] = 'baz' dict2['bar'] = 'bif' print(dict1, dict2) 

Ths outputs:

{'foo': 'bar', 'bar': 'baz'} {'foo': 'bar', 'bar': 'bif'} 

If you want to remove reference to dict1 completely, you can just del dict1.

If you're concerned about references to vars inside the dictionary, you can use deepcopy from the copy module.

See the dict.copy method

There is no such thing as "copy an object into a new variable". You can copy an object; this creates a new object. An object may have 0, 1, or many names (what you are calling a "variable"). It is up to you whether you give the new object a name -- e.g. foo = d.copy() -- or leave it nameless -- e.g. some_function(d.copy()).

An object can be copied with a shallow copy or a deep copy. See the copy module. Does a deep copy achieve what you meant by "without maintaining the link with previous variable"? If not, please clarify.

1

You can access a dict's entry and remove it in one step using dict.pop(). Here is a creation of a dict dd, and then the entry by entry extraction from dd and construction of zz:

>>> dd = dict(zip("ABC","123")) >>> print dd {'A': '1', 'C': '3', 'B': '2'} >>> zz = dict((k,dd.pop(k)) for k in dd.keys()) >>> print zz {'A': '1', 'C': '3', 'B': '2'} >>> print dd {} 

So after creating zz, all of the values have been removed from dd. If you wanted to do something selective, add an if condition to the dict:

>>> dd = dict(zip("ABCDEFGHIJKLMNOPQRSTUVWXYZ", range(1,27))) >>> vowels = "AEIOU" >>> zz = dict((k,dd.pop(k)) for k in dd.keys() if k not in vowels) >>> dd {'A': 1, 'E': 5, 'I': 9, 'O': 15, 'U': 21} >>> zz {'C': 3, 'B': 2, 'D': 4, 'G': 7, 'F': 6, 'H': 8, 'K': 11, 'J': 10, 'M': 13, 'L': 12, 'N': 14, 'Q': 17, 'P': 16 , 'S': 19, 'R': 18, 'T': 20, 'W': 23, 'V': 22, 'Y': 25, 'X': 24, 'Z': 26} 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like