0

I'm trying to add a key to a dictionary with the update() method, but since the program might need to be closed, I need for the key to be saved backed into the file for later use.

If I add the key {'car' : 'purple'} to the dictionary it would save as:

dict = {
        {'truck' : 'blue'},
        {'mini' : 'green'},
        {'car' : 'purple'}

}

instead of in its previous value.

dict = {
        {'truck' : 'blue'},
        {'mini' : 'green'}

}
Bottish
  • 103
  • 4

2 Answers2

1

When you assign a value to a variable, for example the dict type you show, it is not saved in any file. If you want to persist the variable to a file you will need to do something special.

If you work in the Python shell (aka REPL) you can use shelve to persist the name/value pairs.

If you want your own program to save data, that data could be written to a JSON file, or saved in a database.

BTW, it is considered bad practice to name a variable dict because that is also a type.

Also, your use of the term default state would be better expressed as previous value, because you have not indicated that this variable is assigned from a property in an API or framework.

Mike Slinn
  • 7,705
  • 5
  • 51
  • 85
0

You can save the file simply to a text file and import it when need be.

dict = {'truck': 'blue', 'mini': 'green', 'car': 'purple'}
  

new_file = open('newfile.txt', 'wt')
new_file.write(str(dict))
new_file.close()
Krys Tof
  • 21
  • 6