t = p.copy()
u = p.copy()
#split the data by events and participant frames
def remove_events(dictionary):
for frame in dictionary['info']['frames']:
del frame['events']
return dictionary
def remove_participantframes(dictionary):
for frame in dictionary['info']['frames']:
del frame['participantFrames']
return dictionary
t = remove_participantframes(t)
u = remove_events(u)
with open('removed_participantframes.txt', 'w') as f:
json.dump(t, f, indent=2)
with open('removed_events.txt', 'w') as f:
json.dump(u, f, indent=2)
我有一个起始字典p
,我想做两个不同的操作remove_participantframes
和remove_events
来创建两个新字典t
和u
。目前,当上传t
和u
时,它们都有remove_participantframes
和remove_events
操作应用于它们。
作为操作的结果,我希望有两个不同的字典。
问题是你并没有真正复制列表:
id(p['info']['frames']), id(t['info']['frames']), id(u['info']['frames'])
你可以使用deepcopy:
来解决这个问题from copy import deepcopy
t = deepcopy(p)
u = deepcopy(p)
或者生成新的字典:
def remove_events(dictionary):
return {
'info': {
'frames': [
{k: v for k, v in frame.items() if k != 'events'}
for frame in dictionary['info']['frames']
]
}
}
def remove_participantframes(dictionary):
return {
'info': {
'frames': [
{k: v for k, v in frame.items() if k != 'participantFrames'}
for frame in dictionary['info']['frames']
]
}
}
当您使用copy.copy()
时,将创建新对象。然而,孩子们没有被复制,而是被引用。所以,在你的情况下,如果你想有两个不同的字典,你应该使用copy.deepcopy()
。
文档解释了它们之间的区别。