pythondictionarypersistence

How to make changes to a dictionary persistent?


I'm trying to make small app that would calculate charge weight based on stored dict of materials/concentrations.
From time to time the dict needs to be updated and stored for future use.

Below snippet asks a user to provide new values for the dict and then updates it.

baseDict={'a':10, 'b':20, 'c':30, 'd':40}
def updateDict(key, value):
    temp = {key : value}
    baseDict.update(temp)
    return baseDict

key = str(input('Enter key\n'))
value = input('Enter value\n')
baseDict = updateDict(key, value)

The problem is that when the shell is re-started, the baseDict returns to the original values.
I found solutions for similar question from ~ 2010, but they use Pickle, shelve, JSON to store/retrieve the dict in a separate file and load it every time the code is run.

I'm planning to turn the code into a small .exe file to be ran on a py-less computer.
Any suggestions on how to make baseDict stay updated in such environment would be greatly appreciated.

Thank you!


Solution

  • Using json or pickle is better than saving plaintext and ast.literal_evaling it. I would recommend json:

    For json, first run this once:

    import json
    
    with open('baseDict.json', 'w') as f:
        json.dump({'a':10, 'b':20, 'c':30, 'd':40}, f)
    

    Then:

    import json
    
    with open('baseDict.json','r') as f:
        baseDict = json.load(f)
    
    # your code
    
    with open('baseDict.json', 'w') as f:
        json.dump(baseDict, f)
    

    See here for why json is better than ast.literal_eval.