convert dictionary to string

Beni Cherniavsky cben at techunix.technion.ac.il
Fri Apr 11 07:40:09 EDT 2003


Stephen D Evans wrote on 2003-04-10:

>
> d={'A':45.10, 'F':56.50,}
>
> # assuming that you would like 2 decimal places...
>
> s1 = ''.join(['%s%.2f' % item for item in d.iteritems()])
>
> # or without the list comprehension...
>
> s2 = ''
> for (key, value) in d.items():
>     s2 = '%s%s%.2f' % (s2, key, value)
>
Note that the later is using quadratic time.  Joining strings by
appending to them is almost always a bad idea (unless you have very
few of them); ''.join is the recommeded solution for most cases but I
guess [c]StringIO is very effecient too.

-- 
Beni Cherniavsky <cben at tx.technion.ac.il>

Never spend several weeks on a single homework - or you will miss a
nice Linux conference ;-(.





More information about the Python-list mailing list