Copy the dictionary to a new variable without supporting the link from the previous

I want to copy the dictionary to a new variable without supporting the link from the previous variable.

+4
source share
4 answers
from copy import deepcopy new_dict = deepcopy(orig_dict) 

dict.copy () creates small copies, which means that if your dictionary contains other container objects such as a list, tuples, etc., they will be referenced again and not duplicated!

You can try it yourself:

 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 
+9
source

The .copy method in the dictionary should be sufficient.

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

Outputs:

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

If you want to completely remove the link to dict1 , you can simply del dict1 .

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

+6
source

See dict.copy method

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

An object can be copied with a shallow copy or a deep copy. See copy module . Does a deep copy get what you mean by "without saving the link from the previous variable"? If not, please specify.

+4
source

You can access the dict entry and delete it in one step using dict.pop (). Here is creating a dict dd, and then writing it by typing from dd and building 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 values ​​were removed from dd. If you want 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} 
+1
source

Source: https://habr.com/ru/post/1389824/


All Articles