开发者

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

开发者 https://www.devze.com 2023-01-12 02:40 出处:网络
I\'m trying to create a new variable that will consist of an existing dictionary so that I can change things in this new dictionary without it affecti开发者_如何学运维ng the old one. When I try this b

I'm trying to create a new variable that will consist of an existing dictionary so that I can change things in this new dictionary without it affecti开发者_如何学运维ng the old one. When I try this below, which I think would be the obvious way to do this, it still seems to edit my original dictionary when I make edits to the new one.. I have been searching for info on this but can't seem to find anything, any info is appreciated

newdictionary = olddictionary


You're creating a reference, instead of a copy. In order to make a complete copy and leave the original untouched, you need copy.deepcopy(). So:

from copy import deepcopy
dictionary_new = deepcopy(dictionary_old)

Just using a = dict(b) or a = b.copy() will make a shallow copy and leave any lists in your dictionary as references to each other (so that although editing other items won't cause problems, editing the list in one dictionary will cause changes in the other dictionary, too).


You are just giving making newdictionary point to the same reference olddictionary points to. See this page (it's about lists, but it is also applicable to dicts).

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


Use .copy() instead (note: this creates a shallow copy):

newdictionary = olddictionary.copy()

To create a deep copy, you can use .deepcopy() from the copy module

newdictionary = copy.deepcopy(olddictionary)

Wikepedia :

Shallow vs Deep Copy


Assignment like that in Python just makes the newdictionary name refer to the same thing as olddictionary, as you've noticed. You can create a new dictionary with the dict() constructor:

newdictionary = dict(olddictionary)

Note that this makes a shallow copy. For deep copies, see the copy standard library module.


newdictionary = dict(olddictionary.items())

This creates a new copy (more specifically, it feeds the contents of olddict as (key,value) pairs to dict, which constructs a new dictionary from (key,value) pairs).

Edit: Oh yeah, copy - totally forgot it, that's the right way to do it.

a = b

just copies a reference, but not the object.


You are merely creating another reference to the same dictionary.

You need to make a copy: use one of the following (after checking in the docs what each does):

new = dict(old)

new = old.copy()

import copy
new = copy.copy(old)

import copy
new = copy.deepcopy(old)


I think you need a deep copy for what you are asking. See here.

It looks like dict.copy() does a shallow copy, which is what Rick does not want.

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

精彩评论

暂无评论...
验证码 换一张
取 消