List to dict conversion

Gerrit Holl gerrit at nl.linux.org
Fri Oct 3 05:24:18 EDT 2003


<quote name="Wujek" date="1065176228" email="wujek at wujek.com">
> 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]
</quote>

How about:
dict([s.split(':') for s in l])

Don't know if it's faster, simplier or prettier, but I find it easier to read.
This may not be the case if you aren't familiar with list comprehensions, though.

Gerrit.

-- 
Mozilla _is_ the web: it grows faster than you can download it.
1011001 1101111 1110101 1110010 1110011 0101100
1000111 1100101 1110010 1110010 1101001 1110100





More information about the Python-list mailing list