例如,如果我有一个字典的字典或字典的字典,但我只希望“深”复制到两个层次的深度是否有一个简单的方法来做到这一点?在python中,我将如何对特定深度的字典进行深层复制?
我四处张望,看看是否有我可以使用的库或示例,但找不到任何东西。我对Python相当陌生,否则我会自己编写子例程来完成这个任务。有任何想法吗?代码片段将不胜感激,因为它可以让我更快地理解,而不仅仅是解释如何去做。
谢谢。
附加信息:
有些人问我为什么会想这样做,我需要一个副本(而不是裁判,因为我要修改一些值,我不希望原始修改)的一些从字典中的项目,但该字典是巨大的(类型的字典中许多字典),所以我并不想炸掉我的内存占用
到目前为止我的代码
好吧,我给向上。这比我预期的要困难得多,我没有时间弄清楚。我最近尝试了一些调试/测试代码。
# Deep copy any iteratable item to a max depth and defaults to removing the
# rest. If you want to keep the stuff past max depth as references to orig
# pass the argument else_ref=1. Ex:
# dict_copy = copy_to_depth(dict_orig, 2, else_ref=1)
def copy_to_depth(orig, depth, **kwargs):
copy = type(orig)()
for key in orig:
# Cannot find a reliable and consistent way to determine if the item
# is iterable.
#print orig[key].__class__
#if hasattr(orig[key], '__iter__'):
#if hasattr(orig[key], '__contains__'):
#if iterable(orig[key]):
#try:
if hasattr(orig[key], '__contains__'):
if depth > 0:
copy[key] = copy_to_depth(orig[key], depth - 1, **kwargs)
else:
if 'else_ref' in kwargs:
copy[key] = orig[key]
else:
copy[key] = 'PAST_MAX_DPETH_ITERABLE_REMOVED'
#except:
else:
copy[key] = orig[key]
return copy
def iterable(a):
try:
(x for x in a)
return True
except TypeError:
return False
people = {'rebecca': 34, 'dave': 'NA', 'john': 18, 'arr': [9,8,{'a':1,'b':[1,2]}], 'lvl1':
{'arr': [9,8,{'a':1,'b':[1,2]}], 'dave': 'NA', 'john': 18, 'rebecca': 34, 'lvl2':
{'arr': [9,8,{'a':1,'b':[1,2]}], 'dave': 'NA', 'john': 18, 'rebecca': 34, 'lvl3':
{'rebecca': 34, 'dave': 'NA', 'john': 18, 'arr': [9,8,{'a':1,'b':[1,2]}]}}}}
print people
ppl_cpy = copy_to_depth(people, 1)
ppl_cpy['arr'][1] = 'nine' # does not mod orig
ppl_cpy['john'] = 0 # does not mod orig
ppl_cpy['lvl1']['john'] = 1 # does not mod orig b/c copy_to_depth
ppl_cpy['arr'][3]['a'] = 'aie' # does not mod orig
#ppl_cpy['lvl1']['lvl2']['john'] = 2 # Rest cause an error
#ppl_cpy['lvl1']['lvl2']['lvl3']['john'] = 3
print people
print ppl_cpy
ppl_cpy = copy_to_depth(people, 1, else_ref=1)
ppl_cpy['john'] = 0 # does not mod orig
ppl_cpy['lvl1']['john'] = 1 # does not mod orig b/c copy_to_depth was 1
ppl_cpy['lvl1']['lvl2']['john'] = 2 # Rest Do not cause error but modifies orig
ppl_cpy['lvl1']['lvl2']['lvl3']['john'] = 3
print people
print ppl_cpy
I无法找到可靠且一致的方式来确定该项是否可迭代。我一直在阅读this post,并试图找出答案,但没有任何解决方案似乎适用于我的测试案例。
我会深入复制整个字典,并尝试稍后(或不是)优化解决方案。
谢谢...
你希望通过这样做来解决什么问题? – 2012-03-20 20:58:34
你是否尝试过明显的'copy.deepcopy(x)'和'pickle'? – zenpoy 2012-03-20 21:08:00
@zenpoy我看过copy.deepcopy(x),但它似乎没有能力将其副本限制到特定深度。我没有想到使用泡菜,我不知道如何工作,但你的建议让我想,也许你可以得到pprint做的副本,因为它确实让你指定一个深度?我必须考虑如何这将工作。 – stephenmm 2012-03-20 21:25:53