954,546 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Read Dictionaries To/From Files

Hi Guys,

I have a nested dictionary that i would like to be populated from a file at the start of my prog and put back into the file at the end of the prog.

Could anyone direct me to somewhere where i could get info on how to do this??
Or does anyone have any advice on how to go about it..

Thanks!!

StepIre
Newbie Poster
14 posts since Feb 2008
Reputation Points: 17
Solved Threads: 1
 

Hi StepIre,

You could use the pickle module, which serializes and saves data structures, effectively allowing you to skip the whole messy business of file parsing. Example:

import pickle

# If you want to store a dictionary in a file...
d = { "a":"aardvark", "b":"ball", "c":"centurion" }
f = open("somefile.dat", "w")
pickle.dump(d, f)
f.close()

# If you want to load the stored dictionary...
f = open("somefile.dat", "r")
d = pickle.load(f)
f.close()
print d["a"]     # prints 'aardvark'


Is this what you were looking for?

Hope this helps!

G-Do
Junior Poster
147 posts since Jun 2005
Reputation Points: 41
Solved Threads: 31
 

Hey,
thanks for such a quick response..

That actually looks perfect!
Being a newbie i never heard of that module.

Thanks again.. problem solved!

StepIre
Newbie Poster
14 posts since Feb 2008
Reputation Points: 17
Solved Threads: 1
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You