Can't save the data in shelve module Python

I want to create a python file that when user inputs a value, it will save to a dictionary and update the binary file created by shelve module. The problem is that when I run the python file again, the dictionary is not updated. There is no error code or anything and I don't know what to do.

import shelve
menubook = shelve.open('menu_data', writeback=True)

menubookA = {'main':'toast', 'sub':'egg', 'drink':'milk'}

print(menubookA)
print(menubookA['drink']) 

key = input("Enter key: ")
value = input("Enter value: ")

menubookA[key] = value
print(menubookA) # When I check the dictionary here, it has been updated but when I run the program again, the value and key added are gone. 

menubook.close()

I would appreciate if anyone could help me.

1 answer

  • answered 2021-06-23 07:13 leo

    You obviously forgot to write the data back to the file:

    import shelve
    
    menubook = shelve.open("menu_data", writeback=True)
    
    # Read data from the file
    for key, value in menubook.items():
        print("Key: %s = %s" % (key, value))
    
    menubookA = {"main": "toast", "sub": "egg", "drink": "milk"}
    
    print(menubookA)
    print(menubookA["drink"])
    
    key = input("Enter key: ")
    value = input("Enter value: ")
    
    menubookA[key] = value
    print(menubookA)  # When I check the dictionary here, it has been updated but when I run the program again, the value and key added are gone.
    
    # Write data back to the file
    menubook.update(menubookA)
    
    menubook.close()