Python by creating a new variable from a dictionary? not as straightforward as it seems?

I am trying to create a new variable that will consist of an existing dictionary so that I can change things in this new dictionary without affecting the old one. When I try this below, which I think will be the obvious way to do this, it still seems to be editing my original dictionary when I make changes for the new one. I searched for information about this, but can't seem to find anything, any information is appreciated

newdictionary = olddictionary
+3
source share
6 answers

You create a link instead of a copy. To make a full copy and leave the original untouched, you need copy.deepcopy(). So:

from copy import deepcopy
dictionary_new = deepcopy(dictionary_old)

a = dict(b) a = b.copy() ( , , ).

+7

, newdictionary olddictionary. . ( , dicts).

alt text


.copy() ( : ):

newdictionary = olddictionary.copy()

, .deepcopy()

newdictionary = copy.deepcopy(olddictionary)

:

Shallow vs Deep Copy

+6

, Python, , newdictionary , olddictionary, . dict():

newdictionary = dict(olddictionary)

, . . copy.

+3
newdictionary = dict(olddictionary.items())

( , olddict (, ) dict, ( , )).

: , - , .

a = b

, .

+1

.

: ( , ):

new = dict(old)

new = old.copy()

import copy
new = copy.copy(old)

import copy
new = copy.deepcopy(old)
0

, , . . .

, dict.copy() , .

from copy import deepcopy
d = {}
d['names'] = ['Alfred', 'Bertrand']
c = d.copy()
dc = deepcopy(d)
0

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


All Articles