Writing dictionary output to a file
David LeBlanc
whisper at oz.net
Sat Mar 6 04:55:41 EST 2004
> Hey,
> I have a simple problem:
> I have this dictionary output as per the format I
> desired :
> index : value
>
> However, I want to write this to a file, instead of
> just printing out to the std output.
> I tried to make a new string s= i+ ":" +v
> and fwrite(s) to the file. First it does not work.
> Second I loose the relationship of index with the
> value which I dont want. Can some one point me how to
> write this to a file while still preserving index:
> value relationship as it is present in the current
> dictionary.
>
> Sorry for the basic questions, I am struggling with a
> project.
>
> Thx
> Dont
> words = open('dictionary', 'r').read().split()
> dct = {}
> for i in xrange(len(words)):
> dct[words[i]] = i
> #print dct
>
>
> for i, v in enumerate(dct):
> #s= i+":"+v
> print i,":",v
>
How about pickling the dictionary? See the pickle module in the doc.
import pickle
pickle.dump(dct, open('dctfilename.ext', 'w'))
Dave LeBlanc
Seattle, WA USA
More information about the Python-list
mailing list