调用库
import copy
#浅拷贝
new_list = copy.copy(existing_list)
#深拷贝
new_list_of_dicts = copy.deepcopy(existing_list_of_dicts)
手动实现,利用递归
#!/usr/bin/python
# -*- coding: UTF-8 -*-
dt = {"a": "aaa", "b": "bbb", "c": {"c1": 11, "c2": {"c21": "211", "c22": "212", "c23": "213"}, "c3": 33}}
def copy_dict(d):
res = {}
if not d:
return {}
for key, value in d.items():
# 如果不是dict字典,则直接赋值
if not isinstance(value, dict):
res[key] = value
# 如果还是字典,递归调用copy_dict(d)
else:
res[key] = copy_dict(value)
return res
print("复制前:" + str(dt))
copy_dt = copy_dict(dt)
print("复制后:" + str(copy_dict(dt)))
参考链接
https://blog.csdn.net/u014259820/article/details/79505688