List to dict conversion
Alex Martelli
aleax at aleax.it
Fri Oct 3 05:47:15 EDT 2003
Wujek wrote:
> Hi!
>
> From list:
> >>> l
> ['key1:val1', 'key2:val2']
>
> I want dict:
> >>> d
> {'key2': 'val2', 'key1': 'val1'}
>
> Is there any better (faster, simplier, prettier?) solution than this?
> >>> for line in l:
> ... spl=line.split(':')
> ... d[spl[0]] = spl[1]
d = dict([ x.split(':') for x in l ])
should work just the same way as your loop -- perhaps marginally
faster (try both with timeit.py, of course, if it DOES matter...!),
and "simpler" and "prettier" are in the eyes of the beholders.
Alex
More information about the Python-list
mailing list