Alexander Viktorsson
Alexander Viktorsson

Reputation: 27

Saving dictionary to file then loading file to edit dictionary

right now i can use my program to create and edit a dictionary but i need to be able to save the dictionary vaiable to a file and then load that file and replace the old dictionary.

something like this:

Dict1={key:value}
Dict2=Dict1

save Dict2 to file and then load file so i can replace Dict1

Dict1=Dict2

Upvotes: 0

Views: 309

Answers (3)

Nikolai Golub
Nikolai Golub

Reputation: 3567

Use module pickle:

favorite_color = { "lion": "yellow", "kitty": "red" } 
pickle.dump( favorite_color, open( "save.p", "wb" ) )
favorite_color = pickle.load( open( "save.p", "rb" ) )

But notice, that unpickling data from unsecured source could lead to security issues

Upvotes: 2

enthus1ast
enthus1ast

Reputation: 2109

Use json! Json its fast and more secure than eval/pickle. (and btw produces smaller files than pickle) Json won't execute any code (there is no "magic" involved).

import json

# Write to file
d={123:123}
json.dump(d,open("myfile","w"))


# Load from file
d = json.load(open("myfile","r")

Upvotes: 4

sweber
sweber

Reputation: 2976

The easiest way is this:

f=open("myFile", "w")
f.write(dict2)
f.close()

Later:

f=open("myFile", "r")
dict2=eval(f.read())
f.close()

The trick is that the string representation (which will be written to the file) of a dict is something like '{ "lion": "yellow", "kitty": "red" }'

The eval() function interprets this string after reading from file and so returns a dict object.

However: Be careful: Someone may replace the content of the file with python-code to format your hard disk. If you have such concerns about security, you better use something like pickle.

Upvotes: -1

Related Questions