In Python, with two dictionaries, simply doing
dict2 = dict1
Will not cause dict2 to be a distinct copy of dict1. They will point to the same thing, so modifying dict2 will perform the same effect on dict1.
One workaround is
dict2 = dict(dict1)
So if I were to modify dict2, it would not affect dict1’s values.
In my program, I’m currently making a dictionary that’s composed of multiple copies of a previous dictionary. Let’s call the previous dictionary temp2, and the current one temp3. I don’t know how many copies I’ll need in advance, so I thought of doing this:
temp3 = {}
for i in xrange(some_number):
temp3[i] = dict(temp2)
But my debug tests show that if I modify temp3[0]’s dictionary (which, again, is a copy of temp2), then this will also modify temp3[1]’s copy, and temp3[2], etc., so the result is a dictionary that consists of n identical copies of a dictionary, where n = some_number. Does anyone know of a workaround? Thanks.
EDIT: In response to a comment, temp2 is a dictionary composed of values that are lists, so {a: [list1], b: [list2], etc.}.
Try the copy.deepcopy method: http://docs.python.org/2/library/copy.html