【问题标题】:Shelve, Python, updating a dictionary搁置,Python,更新字典
【发布时间】:2012-12-21 20:37:36
【问题描述】:

我在 Python 中使用 Shelve,但遇到了一个问题:

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'}}

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

【问题讨论】:

    标签: python dictionary shelve


    【解决方案1】:

    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
    

    【讨论】:

    • @MorganAllen 没问题 :)
    猜你喜欢
    • 2012-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-30
    • 1970-01-01
    • 1970-01-01
    • 2017-07-18
    相关资源
    最近更新 更多