我遇到一个问题,即我有一个可能会或可能不会更改字典值的函数,并且我想使用另一个函数来跟踪这些更改。看起来像这样:
dict_t0 = my_dict
function_that_alters_values(my_dict)
dict_t1 = my_dict
compare_dicts(dict_t0,dict_t1)
但是,由于dict_t0
仅指向对象my_dict
,因此对my_dict
所做的任何更改都将应用于dict_t0
,这就是我尝试使用的原因
dict_t0 = deepcopy(my_dict)
但是,这给了我以下错误:
RecursionError: maximum recursion depth exceeded
有没有更好的方法来解决我的问题?
答案 0 :(得分:2)
也许您可以更改函数,以使其无法就地运行,而是返回新实例:
original = {1: [1, 2, 3], 2: [4, 5, 6]}
new = original
def squareValues(someDict):
return {k: [i**2 for i in v] for k, v in someDict.items()}
new = squareValues(new)
original
#{1: [1, 2, 3], 2: [4, 5, 6]}
new
#{1: [1, 4, 9], 2: [16, 25, 36]}
编辑
对于deepcopy
,您可以增加递归限制:
sys.setrecursionlimit(5000) # or more if your structure is deeper.
要查看当前的递归限制,请使用:
sys.getrecursionlimit()
答案 1 :(得分:0)
对于Deepcopy问题,您可以遵循@zipa答案。然后,为了比较两个字典,您可以创建一个像这样的函数:
def compare_dicts(d1, d2):
"""
Gives the actions necessary for d1 to be equal to d2
"""
diff = {
"add": [key for key in d2 if key not in d1],
"delete": [key for key in d1 if key not in d2],
"update": {key: d2[key] for key in set(d1) & set(d2) if d1[key] != d2[key]}
}
return diff
用法示例:
dict1 = {
"a": 1, # same
"b": 2, # different value
"c": 3, # not present
#"d": 4 missing
}
dict2 = {
"a": 1,
"b": 1,
"d": 4
}
print(compare_dicts(dict1, dict2))
{
'add': ['d'],
'delete': ['c'],
'update': {'b': 1}
}