Python3.7 辞書をclone (ディープコピー)
copy.deepcopy()
を使う- 辞書の
.copy()
はディープコピーじゃないから注意
Python 3.7.4
copy.deepcopy()
を使う。
import copy
# 元の辞書
dict = {'key1': 'value1', 'nest': {'nested': '^_^'}}
# copy.deepcopy() して key1 を変更
dict1 = copy.deepcopy(dict)
dict1['key1'] = '!!'
# copy.deepcopy() して key2 と nest.nested を変更
dict2 = copy.deepcopy(dict)
dict2['key1'] = '??'
dict2['nest']['nested'] = '-_-'
# 元の辞書に key2 を追加
dict['key2'] = 'value2'
print(dict) # -> {'key1': 'value1', 'nest': {'nested': '^_^'}, 'key2': 'value2'}
print(dict1) # -> {'key1': '!!', 'nest': {'nested': '^_^'}}
print(dict2) # -> {'key1': '??', 'nest': {'nested': '-_-'}}
辞書に .copy()
というインターフェースがあるけど、これはディープコピーではない。
import copy
# 元の辞書
dict = {'key1': 'value1', 'nest': {'nested': '^_^'}}
# .copy() して key1 を変更
dict1 = dict.copy()
dict1['key1'] = '!!'
# .copy() して key2 と nest.nested を変更
dict2 = dict.copy()
dict2['key1'] = '??'
dict2['nest']['nested'] = '-_-' # <- これが dict, dict1, dict2 の全てに反映される!
# 元の辞書に key2 を追加
dict['key2'] = 'value2'
print(dict) # -> {'key1': 'value1', 'nest': {'nested': '-_-'}, 'key2': 'value2'}
print(dict1) # -> {'key1': '!!', 'nest': {'nested': '-_-'}}
print(dict2) # -> {'key1': '??', 'nest': {'nested': '-_-'}}