首页 > python中 shelve 和 dict 为什么会有这个区别?

python中 shelve 和 dict 为什么会有这个区别?

初学者,在使用shelve的时候有一些疑问:

test_dict = {}
test_dict['key'] = {'a': 1, 'b': 2}
test_dict['key']['a'] = 3
print test_dict['key']

test_dict1 = {}
test_dict2 = test_dict1
test_dict2['key'] = {'a': 1, 'b': 2}
test_dict2['key']['a'] = 3
print test_dict1['key']

import shelve
test_shelve = shelve.open('file')
test_shelve['key'] = {'a': 1, 'b': 2}
test_shelve['key']['a'] = 3
print test_shelve['key']

temp = test_shelve['key'] 
temp['a'] = 3
test_shelve['key'] = temp
print test_shelve['key']

输出

{'a': 3, 'b': 2}
{'a': 3, 'b': 2}
{'a': 1, 'b': 2}
{'a': 3, 'b': 2}

需要定义一个临时变量才可以完成同样的更新。
我想知道第二段和第三段有什么区别
特别是给第三段 test_shelve['key']['a'] 赋值的时候,到底发生了什么


把你第三段的test_shelve = shelve.open('file')换成test_shelve = shelve.open('file', writeback = True)

https://docs.python.org/2.7/library/shelve.html?highlight=writeback

【热门文章】
【热门文章】