Search code examples
pythonshelve

Shelve - Appending a new value


This is how my DB in shelve looks like

{"admin" : {"user1" : ["their info"]} }

I have this code which works to append a new value

dict["admin"]["user2"] = ["their info]

But for some reason when I implement shelve, it doesn't work. Is there anything wrong with my code or shelve?

Btw this is the code i use to open the db

a = shelve.open('user.db')

Solution

  • The problem is shelve doesn't know when the variables in it are internally mutated. It only tracks modifications to the shelf its(h)elf. You'll have to unshelf the object, modify it, then reassign it for the changes to be saved.

    shelf = shelve.open(...)
    obj = shelf["admin"]   # <- unshelve
    obj["user2"] = "info"  # <- mutate
    shelf["admin"] = obj   # <- reshelve