[Tutor] How do I save a dictionary to disk? (another
newbie question)
Kirby Urner
urnerk@qwest.net
Thu, 10 Jan 2002 23:00:49 -0800
>def add_name():
> print "Enter Name"
> n=raw_input()
> d1[n]=m
^
This can't work as written as m is nowhere defined.
If you want the dictionary to persist, you need to
save it as a file after the user quits. Probably
best to save it as a human readable file. Lots of
ways to parse it out and back in.
Note: d1.items() spits out a list of (key,value)
pairs.
try:
f = open("output.txt","w")
for i in d1.items():
f.write("%s,%s\n" % (i[0],i[1]))
finally:
f.close()
would create:
name,1111
different name,2222
a. name,1111
or whatever else was in the dictionary, as a text file
with line feeds between key,value pairs.
try:
f=open("test.txt","r")
dlist=[j.split(",") for j in f.readlines()]
finally:
f.close()
d1={}
for pair in dlist:
d1[pair[0]] = pair[1][:-1]
would recreate the dictionary from the saved file, if
included at the top of your module.
Kirby