Search This Blog

Friday, October 31, 2008

How to write & read a dictionary in File

Using Pickle in Python for dumping and reading a Dictionary from a file



D1 = {'I':1,'II':2,'III':3,'IV':4,'V':5,'VI':6,'VII':7,'VIII':8,'IX':9,'X':10}

# to save a Python object like a dictionary to a file
# and load it back intact you have to use the pickle module

import pickle

print "The original dictionary:"
print romanD1

file = open("abc.dat", "w")
pickle.dump(D1, file)
file.close()

# now load the dictionay object back from the file ...
file = open("abc.dat", "r")
D2 = pickle.load(file)
file.close()

print "Dictionary after pickle.dump() and pickle.load():"
print D2

No comments: