(不知道如何最好地表達問題標題)
我有類似以下的情況:
In [1]: t = {1:2}
In [2]: x = {'a' : t, 'b' : t}
In [3]: x
Out[3]: {'a': {1: 2}, 'b': {1: 2}}
In [4]: x['a'].update({1:4})
In [5]: x
Out[5]: {'a': {1: 4}, 'b': {1: 4}}
In [6]:
但是字典比較復雜。
我想確保字典中的任何元素都不會參考字典中的任何其他元素,以便我能夠在不影響其他元素的情況下更新它的子部分。
理想情況下,我想要類似的東西:
t = {1:2}
x = {'a' : t, 'b' : t}
x = f(x)
x['a'].update({1:4})
# x is now: {'a': {1: 4}, 'b': {1: 2}}
編輯 - 附加資訊
之前的測驗用例不夠深入。
def get_dict():
d1 = {
1.0: "something",
2.0: "other",
}
d2 = {"z": d1}
tst = {
"main_key": {
"x": d2,
"y": d2,
}
}
return tst
使用這個功能我有:
from copy import deepcopy
tst = get_dict()
tst = deepcopy(tst)
tst["main_key"]["x"].update({1: "check"})
哪些輸出:
{'main_key': {'x': {1: 'check', 'z': {1.0: 'something', 2.0: 'other'}},
'y': {1: 'check', 'z': {1.0: 'something', 2.0: 'other'}}}}
而不是預期的:
{'main_key': {'x': {1: 'check', 'z': {1.0: 'something', 2.0: 'other'}},
'y': {1: 'something', 'z': {1.0: 'something', 2.0: 'other'}}}}
uj5u.com熱心網友回復:
為簡化起見,當您這樣做時b = deepcopy(a),這意味著 inb中的嵌套字典與 中的嵌套字典不同a,但它不會破壞內部結構。可通過不同鍵訪問的字典仍然相同,回圈字典(例如a[some_key] is a)保持回圈。
解決此問題的最佳方法是首先確保您的字典沒有任何不需要的共享參考,例如執行以下操作:
return {
"main_key": {
"x": d2,
"y": deepcopy(d2),
}
}
但是如果你不控制資料到達的方式,你可以使用這樣的遞回函式:
def copy_tree(original):
'''Creates a deep copy of a dictionary, but the copy will
be a tree, so no shared references. Cyclic dictionaries will
cause a recursion error.
All keys, and all non-dictionary values are not copied but used
as-is.'''
if isinstance(original, dict):
return {key: copy_tree(value) for key, value in original.items()}
return original
uj5u.com熱心網友回復:
您可以在 .copy() 上使用t。
t = {1:2}
x = {'a' : t.copy(), 'b' : t.copy()}
print(x) #{'a': {1: 2}, 'b': {1: 2}}
x['a'].update({1:4})
print(x) #{'a': {1: 4}, 'b': {1: 2}}
uj5u.com熱心網友回復:
您可以使用deepcopyfrom copy創建字典的新副本:
from copy import deepcopy
x = deepcopy(x)
x['a'].update({1: 4})
#x: {'a': {1: 4}, 'b': {1: 4}}
#t: {1: 2}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/386394.html
上一篇:字典將另一個字典附加到特定鍵
