从原始字典创建两个不同的字典


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_participantframesremove_events来创建两个新字典tu。目前,当上传tu时,它们都有remove_participantframesremove_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()

文档解释了它们之间的区别。

最新更新