2012-12-21 54 views
1

我与搁置的工作在Python,我有一个问题:搁置,Python和更新字典

In [391]: x 
Out[391]: {'broken': {'position': 25, 'page': 1, 'letter': 'a'}} 

In [392]: x['broken'].update({'page':1,'position':25,'letter':'b'}) 

In [393]: x 
Out[393]: {'broken': {'position': 25, 'page': 1, 'letter': 'a'}} 

我不明白为什么它不更新?有什么想法吗?

回答

10

这包括在documentation。基本上,关键字参数writebackshelve.open负责本:

如果可选writeback参数设置为True,所有参赛作品 访问也被缓存在内存中,并在sync()close()写回;这可以更容易地修改 持久性字典中的可变条目,但是,如果访问很多条目,它可能会消耗大量的缓存内存,并且它可以使关闭操作非常缓慢,因为所有访问的条目都是写回 (没有办法确定哪些访问的条目是可变的,也不知道哪些实际上是变异的)。在同一页面

例子:

d = shelve.open(filename) # open -- file may get suffix added by low-level 
          # library 
# as d was opened WITHOUT writeback=True, beware: 
d['xx'] = range(4) # this works as expected, but... 
d['xx'].append(5) # *this doesn't!* -- d['xx'] is STILL range(4)! 

# having opened d without writeback=True, you need to code carefully: 
temp = d['xx']  # extracts the copy 
temp.append(5)  # mutates the copy 
d['xx'] = temp  # stores the copy right back, to persist it 

# or, d=shelve.open(filename,writeback=True) would let you just code 
# d['xx'].append(5) and have it work as expected, BUT it would also 
# consume more memory and make the d.close() operation slower. 
d.close()  # close it 
+0

gaah ......我错过了。非常感谢。 –

+0

@MorganAllen没问题:) –