Writing dictionary output to a file

Ruud de Jong ruud.de.jong at consunet.nl
Sat Mar 6 05:38:49 EST 2004


dont bother schreef:
> 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.

That is because, per your example, i is an integer,
not a string. s = str(i)+":"+v would 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.

Entries in a dictionary are not sorted. But, in
your example, you already have the index in the
dictionary. Why don't you use that:

indexList = [(i,w) for w, i in dct.iteritems()]
indexList.sort()
for i, v in indexList:
     s = int(i) + ":" + v
     print s

Note that here you are basically rebuilding the list
that you started out with. So, another alternative would
be to keep that list around, and use that as the source
for printing:

for i, w in enumerate(words):
    s = int(i) + ":" + v
    print s

Regards,

Ruud.

> 
> 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
> 
> __________________________________
> Do you Yahoo!?
> Yahoo! Search - Find what you’re looking for faster
> http://search.yahoo.com
> 




More information about the Python-list mailing list