Search code examples
pythonpython-3.xshelve

How to set value in shelve


I want to store dictionary in shelve and also want to put data in that. How can i do that?

import shelve

s = shelve.open("test")
s['flag'] = {}

Solution

  • You cannot edit values directly, so you have to update a copy and then reset it:

    import shelve
    
    s = shelve.open("test")
    s['flag'] = {}
    temp = s['flag']
    temp['foo'] = 'bar'
    s['flag'] = temp
    

    you cannot do

    s['flag']['foo'] = 'bar'
    

    directly because s['flag'] returns a copy