ChatGPT解决这个技术问题 Extra ChatGPT

How to copy a dictionary and only edit the copy

I set dict2 = dict1. When I edit dict2, the original dict1 also changes. Why?

>>> dict1 = {"key1": "value1", "key2": "value2"}
>>> dict2 = dict1
>>> dict2["key2"] = "WHY?!"
>>> dict1
{'key2': 'WHY?!', 'key1': 'value1'}
PythonTutor is great for visualizing Python references. Here's this code at the last step. You can see dict1 and dict2 point to the same dict.
Just in case PythonTutor goes down, here's a screenshot of the data structures at the end.

M
Mike Graham

Python never implicitly copies objects. When you set dict2 = dict1, you are making them refer to the same exact dict object, so when you mutate it, all references to it keep referring to the object in its current state.

If you want to copy the dict (which is rare), you have to do so explicitly with

dict2 = dict(dict1)

or

dict2 = dict1.copy()

It might be better to say "dict2 and dict1 point to the same dictionary", you are not changing dict1 or dict2 but what they point to.
Also note that the dict.copy() is shallow, if there is a nested list/etc in there changes will be applied to both. IIRC. Deepcopy will avoid that.
It is not quite correct that python never implicitly copies objects. Primitive data types, such as int, float, and bool, are also treated as objects (just do a dir(1) to see that), but they are implicitly copied.
@danielkullmann, I think you might have misunderstandings about Python based on how other languages you've dealt with work. In Python, a) There is no concept of "primitive data types". int, float, and bool instances are real Python objects, and b) objects of these types are not implicitly copied when you pass them, not at a semantic Python level for sure and not even as an implementation detail in CPython.
Unsubstantiated rhetoric like "Deep copy is considered harmful" is unhelpful. All else being equal, shallow copying a complex data structure is significantly more likely to yield unexpected edge case issues than deep copying the same structure. A copy in which modifications modify the original object isn't a copy; it's a bug. Ergo, most use cases absolutely should call copy.deepcopy() rather than dict() or dict.copy(). Imran's concise answer is on the right side of sanity, unlike this answer.
I
Imran

When you assign dict2 = dict1, you are not making a copy of dict1, it results in dict2 being just another name for dict1.

To copy the mutable types like dictionaries, use copy / deepcopy of the copy module.

import copy

dict2 = copy.deepcopy(dict1)

For any dictionary I ever work with, deepcopy is what I need... I just lost several hours due to a bug that was because I wasn't getting a complete copy of a nested dictionary and my changes to nested entries were affecting the original.
Same here. deepcopy() does the trick. Was messing up my nested dicts inside a rotating cache by adding a timestamp to a 'copy' of the original event. Thank you!
This actually should be marked as the correct answer; This answer is general and it works for a dictionary of dictionaries as well.
This should be the accepted answer. The unsubstantiated "Deep copy is considered harmful" rhetoric embedded in the comment section of the current accepted answer blatantly invites synchronization woes when copying nested dictionaries (such as those documented here) and should be challenged as such.
Thank you, deepcopy() was what I needed! Seems a bit odd that copy() still holds refs to the original, but hey ho.
a
alukach

While dict.copy() and dict(dict1) generates a copy, they are only shallow copies. If you want a deep copy, copy.deepcopy(dict1) is required. An example:

>>> source = {'a': 1, 'b': {'m': 4, 'n': 5, 'o': 6}, 'c': 3}
>>> copy1 = x.copy()
>>> copy2 = dict(x)
>>> import copy
>>> copy3 = copy.deepcopy(x)
>>> source['a'] = 10  # a change to first-level properties won't affect copies
>>> source
{'a': 10, 'c': 3, 'b': {'m': 4, 'o': 6, 'n': 5}}
>>> copy1
{'a': 1, 'c': 3, 'b': {'m': 4, 'o': 6, 'n': 5}}
>>> copy2
{'a': 1, 'c': 3, 'b': {'m': 4, 'o': 6, 'n': 5}}
>>> copy3
{'a': 1, 'c': 3, 'b': {'m': 4, 'o': 6, 'n': 5}}
>>> source['b']['m'] = 40  # a change to deep properties WILL affect shallow copies 'b.m' property
>>> source
{'a': 10, 'c': 3, 'b': {'m': 40, 'o': 6, 'n': 5}}
>>> copy1
{'a': 1, 'c': 3, 'b': {'m': 40, 'o': 6, 'n': 5}}
>>> copy2
{'a': 1, 'c': 3, 'b': {'m': 40, 'o': 6, 'n': 5}}
>>> copy3  # Deep copy's 'b.m' property is unaffected
{'a': 1, 'c': 3, 'b': {'m': 4, 'o': 6, 'n': 5}}

Regarding shallow vs deep copies, from the Python copy module docs:

The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances): A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original. A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.


this should be the right answer as it doesn't to explicitly loop over the dict and can be used for other primary structures.
Just to clarify: w=copy.deepcopy(x) is the key line.
What is the difference between dict2 = dict1 and dict2 = copy.deepcopy(dict1) ?
@TheTank, y=x makes the two names(references) refer to a same object, i.e. "y is x" is True. Any change made on the object through x is equivalent to a same change through y. However u, v, w are references to new different objects which have values copied from x during instantiation though. As for the differences between u,v(shallow copy) and w(deepcopy), please check docs.python.org/2/library/copy.html
V
Vkreddy

In Depth and an easy way to remember:

Whenever you do dict2 = dict1, dict2 refers to dict1. Both dict1 and dict2 points to the same location in the memory. This is just a normal case while working with mutable objects in python. When you are working with mutable objects in python you must be careful as it is hard to debug.

Instead of using dict2 = dict1, you should be using copy(shallow copy) and deepcopy method from python's copy module to separate dict2 from dict1.

The correct way is:

>>> dict1 = {"key1": "value1", "key2": "value2"}
>>> dict2 = dict1.copy()
>>> dict2
{'key1': 'value1', 'key2': 'value2'}
>>> dict2["key2"] = "WHY?"
>>> dict2
{'key1': 'value1', 'key2': 'WHY?'}
>>> dict1
{'key1': 'value1', 'key2': 'value2'}
>>> id(dict1)
140641178056312
>>> id(dict2)
140641176198960
>>> 

As you can see the id of both dict1 and dict2 are different, which means both are pointing/referencing to different locations in the memory.

This solution works for dictionaries with immutable values, this is not the correct solution for those with mutable values.

Eg:

>>> import copy
>>> dict1 = {"key1" : "value1", "key2": {"mutable": True}}
>>> dict2 = dict1.copy()
>>> dict2
{'key1': 'value1', 'key2': {'mutable': True}}
>>> dict2["key2"]["mutable"] = False
>>> dict2
{'key1': 'value1', 'key2': {'mutable': False}}
>>> dict1
{'key1': 'value1', 'key2': {'mutable': False}}
>>> id(dict1)
140641197660704
>>> id(dict2)
140641196407832
>>> id(dict1["key2"])
140641176198960
>>> id(dict2["key2"])
140641176198960

You can see that even though we applied copy for dict1, the value of mutable is changed to false on both dict2 and dict1 even though we only change it on dict2. This is because we changed the value of a mutable dict part of the dict1. When we apply a copy on dict, it will only do a shallow copy which means it copies all the immutable values into a new dict and does not copy the mutable values but it will reference them.

The ultimate solution is to do a deepycopy of dict1 to completely create a new dict with all the values copied, including mutable values.

>>>import copy
>>> dict1 = {"key1" : "value1", "key2": {"mutable": True}}
>>> dict2 = copy.deepcopy(dict1)
>>> dict2
{'key1': 'value1', 'key2': {'mutable': True}}
>>> id(dict1)
140641196228824
>>> id(dict2)
140641197662072
>>> id(dict1["key2"])
140641178056312
>>> id(dict2["key2"])
140641197662000
>>> dict2["key2"]["mutable"] = False
>>> dict2
{'key1': 'value1', 'key2': {'mutable': False}}
>>> dict1
{'key1': 'value1', 'key2': {'mutable': True}}

As you can see, id's are different, it means that dict2 is completely a new dict with all the values in dict1.

Deepcopy needs to be used if whenever you want to change any of the mutable values without affecting the original dict. If not you can use shallow copy. Deepcopy is slow as it works recursively to copy any nested values in the original dict and also takes extra memory.


P
PabTorre

On python 3.5+ there is an easier way to achieve a shallow copy by using the ** unpackaging operator. Defined by Pep 448.

>>>dict1 = {"key1": "value1", "key2": "value2"}
>>>dict2 = {**dict1}
>>>print(dict2)
{'key1': 'value1', 'key2': 'value2'}
>>>dict2["key2"] = "WHY?!"
>>>print(dict1)
{'key1': 'value1', 'key2': 'value2'}
>>>print(dict2)
{'key1': 'value1', 'key2': 'WHY?!'}

** unpackages the dictionary into a new dictionary that is then assigned to dict2.

We can also confirm that each dictionary has a distinct id.

>>>id(dict1)
 178192816

>>>id(dict2)
 178192600

If a deep copy is needed then copy.deepcopy() is still the way to go.


This looks awfully like pointers in C++. Nice for accomplishing the task, but readability wise I tend to dislike this type of operators.
It does have a kind of c'ish look... but when merging together multiple dictionaries, the syntax does look pretty smooth.
Be careful with that, it performs only a shallow copy.
you are right @SebastianDressler, i'll makde adjustments. thnx.
Usefull if you want create copy with some spicies: dict2 = {**dict1, 'key3':'value3'}
A
Akay Nirala

The best and the easiest ways to create a copy of a dict in both Python 2.7 and 3 are...

To create a copy of simple(single-level) dictionary:

1. Using dict() method, instead of generating a reference that points to the existing dict.

my_dict1 = dict()
my_dict1["message"] = "Hello Python"
print(my_dict1)  # {'message':'Hello Python'}

my_dict2 = dict(my_dict1)
print(my_dict2)  # {'message':'Hello Python'}

# Made changes in my_dict1 
my_dict1["name"] = "Emrit"
print(my_dict1)  # {'message':'Hello Python', 'name' : 'Emrit'}
print(my_dict2)  # {'message':'Hello Python'}

2. Using the built-in update() method of python dictionary.

my_dict2 = dict()
my_dict2.update(my_dict1)
print(my_dict2)  # {'message':'Hello Python'}

# Made changes in my_dict1 
my_dict1["name"] = "Emrit"
print(my_dict1)  # {'message':'Hello Python', 'name' : 'Emrit'}
print(my_dict2)  # {'message':'Hello Python'}

To create a copy of nested or complex dictionary:

Use the built-in copy module, which provides a generic shallow and deep copy operations. This module is present in both Python 2.7 and 3.*

import copy

my_dict2 = copy.deepcopy(my_dict1)

I believe dict() creates a shallow copy not a deep copy. Meaning that if you have a nested dict then the outer dict will be a copy but the inner dict will be a reference to the original inner dict.
@shmuels yes, both of these methods will create a shallow copy, not the deep one. See, the updated answer.
D
Dashing Adam Hughes

You can also just make a new dictionary with a dictionary comprehension. This avoids importing copy.

dout = dict((k,v) for k,v in mydict.items())

Of course in python >= 2.7 you can do:

dout = {k:v for k,v in mydict.items()}

But for backwards compat., the top method is better.


This is particularly useful if you want more control over how and what exactly is copied. +1
Note that this method does not perform a deep copy, and if you want a shallow copy with no need to control over keys to be copied, d2 = dict.copy(d1) doesn't require any imports either.
@JarekPiórkowski: or you can call a method like a method: d2 = d1.copy()
Note that you don't need the comprehension in the first example. dict.items already returns a key/value pair iterable. So you can just use dict(mydict.items()) (you can also just use dict(mydict)). It may be useful to have the comprehension if you wanted to filter the entries.
d
d4rty

In addition to the other provided solutions, you can use ** to integrate the dictionary into an empty dictionary, e.g.,

shallow_copy_of_other_dict = {**other_dict}.

Now you will have a "shallow" copy of other_dict.

Applied to your example:

>>> dict1 = {"key1": "value1", "key2": "value2"}
>>> dict2 = {**dict1}
>>> dict2
{'key1': 'value1', 'key2': 'value2'}
>>> dict2["key2"] = "WHY?!"
>>> dict1
{'key1': 'value1', 'key2': 'value2'}
>>>

Pointer: Difference between shallow and deep copys


This results in a shallow copy, not a deep copy.
I was trying this but having trouble. This only works for python 3.5 and up. python.org/dev/peps/pep-0448
l
loosen

Assignment statements in Python do not copy objects, they create bindings between a target and an object.

so, dict2 = dict1, it results another binding between dict2and the object that dict1 refer to.

if you want to copy a dict, you can use the copy module. The copy module has two interface:

copy.copy(x)
Return a shallow copy of x.

copy.deepcopy(x)
Return a deep copy of x.

The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):

A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

For example, in python 2.7.9:

>>> import copy
>>> a = [1,2,3,4,['a', 'b']]
>>> b = a
>>> c = copy.copy(a)
>>> d = copy.deepcopy(a)
>>> a.append(5)
>>> a[4].append('c')

and the result is:

>>> a
[1, 2, 3, 4, ['a', 'b', 'c'], 5]
>>> b
[1, 2, 3, 4, ['a', 'b', 'c'], 5]
>>> c
[1, 2, 3, 4, ['a', 'b', 'c']]
>>> d
[1, 2, 3, 4, ['a', 'b']]

F
Frerich Raabe

You can copy and edit the newly constructed copy in one go by calling the dict constructor with additional keyword arguments:

>>> dict1 = {"key1": "value1", "key2": "value2"}
>>> dict2 = dict(dict1, key2="WHY?!")
>>> dict1
{'key2': 'value2', 'key1': 'value1'}
>>> dict2
{'key2': 'WHY?!', 'key1': 'value1'}

The only oneliner answer that allow immutable add to a dict
C
Craig McQueen

This confused me too, initially, because I was coming from a C background.

In C, a variable is a location in memory with a defined type. Assigning to a variable copies the data into the variable's memory location.

But in Python, variables act more like pointers to objects. So assigning one variable to another doesn't make a copy, it just makes that variable name point to the same object.


python variables act more like c++ references
Because everything in Python is an object! diveintopython.net/getting_to_know_python/… (yes, this response is many years late, but perhaps it's of some use to someone!)
I believe that Python language semantics say there are no "variables". They are called "named references"; meaning the reference to an object is a syntactic string in code. An object can have many named references to it. Immutable objects like ints and floats and str instances have only one instance of it per process. An int of 1 in memory does not change to a 2 or some other value at the same memory address when you do this myvalue=1 myvalue=2
P
Petrus Theron

dict1 is a symbol that references an underlying dictionary object. Assigning dict1 to dict2 merely assigns the same reference. Changing a key's value via the dict2 symbol changes the underlying object, which also affects dict1. This is confusing.

It is far easier to reason about immutable values than references, so make copies whenever possible:

person = {'name': 'Mary', 'age': 25}
one_year_later = {**person, 'age': 26}  # does not mutate person dict

This is syntactically the same as:

one_year_later = dict(person, age=26)

w
wisty

Every variable in python (stuff like dict1 or str or __builtins__ is a pointer to some hidden platonic "object" inside the machine.

If you set dict1 = dict2,you just point dict1 to the same object (or memory location, or whatever analogy you like) as dict2. Now, the object referenced by dict1 is the same object referenced by dict2.

You can check: dict1 is dict2 should be True. Also, id(dict1) should be the same as id(dict2).

You want dict1 = copy(dict2), or dict1 = deepcopy(dict2).

The difference between copy and deepcopy? deepcopy will make sure that the elements of dict2 (did you point it at a list?) are also copies.

I don't use deepcopy much - it's usually poor practice to write code that needs it (in my opinion).


I just realized I need to always be using deepcopy so that when I copy a nested dictionary and start modifying nested entries, the effects occur only on the copy and not the original.
佚名

dict2 = dict1 does not copy the dictionary. It simply gives you the programmer a second way (dict2) to refer to the same dictionary.


i
imcaozi
>>> dict2 = dict1
# dict2 is bind to the same Dict object which binds to dict1, so if you modify dict2, you will modify the dict1

There are many ways to copy Dict object, I simply use

dict_1 = {
           'a':1,
           'b':2
         }
dict_2 = {}
dict_2.update(dict_1)

dict_2 = dict_1.copy() is much more efficient and logical.
Note that if you have a dict inside dict1, with dict_1.copy() the changes you do on the inner dict in dict_2 are also applied to the inner dict in dict_1. In this case you should use copy.deepcopy(dict_1) instead.
x
xaxxon

the following code, which is on dicts which follows json syntax more than 3 times faster than deepcopy

def CopyDict(dSrc):
    try:
        return json.loads(json.dumps(dSrc))
    except Exception as e:
        Logger.warning("Can't copy dict the preferred way:"+str(dSrc))
        return deepcopy(dSrc)

p
personal_cloud

As others have explained, the built-in dict does not do what you want. But in Python2 (and probably 3 too) you can easily create a ValueDict class that copies with = so you can be sure that the original will not change.

class ValueDict(dict):

    def __ilshift__(self, args):
        result = ValueDict(self)
        if isinstance(args, dict):
            dict.update(result, args)
        else:
            dict.__setitem__(result, *args)
        return result # Pythonic LVALUE modification

    def __irshift__(self, args):
        result = ValueDict(self)
        dict.__delitem__(result, args)
        return result # Pythonic LVALUE modification

    def __setitem__(self, k, v):
        raise AttributeError, \
            "Use \"value_dict<<='%s', ...\" instead of \"d[%s] = ...\"" % (k,k)

    def __delitem__(self, k):
        raise AttributeError, \
            "Use \"value_dict>>='%s'\" instead of \"del d[%s]" % (k,k)

    def update(self, d2):
        raise AttributeError, \
            "Use \"value_dict<<=dict2\" instead of \"value_dict.update(dict2)\""


# test
d = ValueDict()

d <<='apples', 5
d <<='pears', 8
print "d =", d

e = d
e <<='bananas', 1
print "e =", e
print "d =", d

d >>='pears'
print "d =", d
d <<={'blueberries': 2, 'watermelons': 315}
print "d =", d
print "e =", e
print "e['bananas'] =", e['bananas']


# result
d = {'apples': 5, 'pears': 8}
e = {'apples': 5, 'pears': 8, 'bananas': 1}
d = {'apples': 5, 'pears': 8}
d = {'apples': 5}
d = {'watermelons': 315, 'blueberries': 2, 'apples': 5}
e = {'apples': 5, 'pears': 8, 'bananas': 1}
e['bananas'] = 1

# e[0]=3
# would give:
# AttributeError: Use "value_dict<<='0', ..." instead of "d[0] = ..."

Please refer to the lvalue modification pattern discussed here: Python 2.7 - clean syntax for lvalue modification. The key observation is that str and int behave as values in Python (even though they're actually immutable objects under the hood). While you're observing that, please also observe that nothing is magically special about str or int. dict can be used in much the same ways, and I can think of many cases where ValueDict makes sense.


A
Anushk

i ran into a peculiar behavior when trying to deep copy dictionary property of class w/o assigning it to variable

new = copy.deepcopy(my_class.a) doesn't work i.e. modifying new modifies my_class.a

but if you do old = my_class.a and then new = copy.deepcopy(old) it works perfectly i.e. modifying new does not affect my_class.a

I am not sure why this happens, but hope it helps save some hours! :)


So how do you make a deepcopy of my_class.a?
Not the best way. Good response is bellow.
J
Jesper Joachim Sørensen

Copying by using a for loop:

orig = {"X2": 674.5, "X3": 245.0}

copy = {}
for key in orig:
    copy[key] = orig[key]

print(orig) # {'X2': 674.5, 'X3': 245.0}
print(copy) # {'X2': 674.5, 'X3': 245.0}
copy["X2"] = 808
print(orig) # {'X2': 674.5, 'X3': 245.0}
print(copy) # {'X2': 808, 'X3': 245.0}

This only works for simple dictionaries. Why not use deepcopy, which is built expressly for this purpose?
Not the best way. Good response is bellow.
somehow none of the "copies" worked for me. Only this way it works. Another better way to write this would be using dictionary comprehension; like this: def _copy_dict(dictionary:dict): return {key: dictionary[key] for key in dictionary}
V
Viiik

You can use directly:

dict2 = eval(repr(dict1))

where object dict2 is an independent copy of dict1, so you can modify dict2 without affecting dict1.

This works for any kind of object.


This answer is incorrect, and should not be used. A user-defined class, for example, may not have an appropriate __repr__ to be reconstructed by eval, nor may the object's class be in the current scope to be called. Even sticking with built-in types, this will fail if the same object is stored under multiple keys, as dict2 would then have two separate objects. A self-referential dictionary, where dict1 contains itself, will instead contain Ellipsis. It would be better to use dict1.copy()
Objects (or "values") are not expected to always have a faithful representation by character strings, not in a usual human readable way in any case.
O
Onkar

Another cleaner way would be using json. see below code

>>> a = [{"name":"Onkar","Address": {"state":"MH","country":"India","innerAddress":{"city":"Pune"}}}]
>>> b = json.dumps(a)
>>> b = json.loads(b)
>>> id(a)
2334461105416
>>> id(b)
2334461105224
>>> a[0]["Address"]["innerAddress"]["city"]="Nagpur"
>>> a
[{'name': 'Onkar', 'Address': {'state': 'MH', 'country': 'India', 'innerAddress': {'city': 'Nagpur'}}}]
>>> b
[{'name': 'Onkar', 'Address': {'state': 'MH', 'country': 'India', 'innerAddress': {'city': 'Pune'}}}]
>>> id(a[0]["Address"]["innerAddress"])
2334460618376
>>> id(b[0]["Address"]["innerAddress"])
2334424569880

To create another dictionary do json.dumps() and then json.loads() on the same dictionary object. You will have separate dict object.


This only works for json-serializable entries and incurs a great overhead.