When you copy the list:
temp_original_list = original_list[:]
you only do a shallow copy, i.e. the new list contains references to the same objects that were in the original list. As the objects within the list are mutable dictionaries, you will need to do a deep copy of the list:
import copy
temp_original_list = copy.deepcopy(original_list)
This will recursively copy the objects within containers and create new versions of those, too.
From the documentation:
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.
Strictly speaking, your problem isn't related as much to the dictionaries as to the lists they hold in turn (e.g. original_list[0]['entry1']
). On this line:
new_dict[key] = line[key]
you are referencing the same list object in new_dict
as was in original_list
. Therefore when you mutate it, e.g.:
new_dict[key].append(1)
this change also appears in the original dictionary. You could therefore also have solved this by making the inner list a copy (only shallow copy required here, as it contains immutable values rather than mutable containers):
new_dict[key] = line[key][:]