You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python字典复制后执行不同操作却出现重复修改的技术问题求助

问题根源

你用的p.copy()是浅拷贝,只会复制字典的顶层结构,但dictionary['info']['frames']里的每个frame字典还是和原字典p里的引用指向同一个对象。所以修改t里的frame时,u里的对应frame也会被改动,最终导致两个字典都被应用了两种操作。

修复代码

改用copy.deepcopy()做深拷贝,让t和u成为完全独立的对象,互不影响:

import copy

# 用深拷贝生成独立副本
t = copy.deepcopy(p)
u = copy.deepcopy(p)

# 拆分数据:移除events和participantFrames
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)
关键区别
  • 浅拷贝(dict.copy()/copy.copy()):仅复制顶层容器,嵌套的可变对象(列表、字典等)仍共享引用
  • 深拷贝(copy.deepcopy()):递归复制所有嵌套的可变对象,生成完全独立的副本

内容的提问来源于stack exchange,提问作者Jack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 23:33:30