Is there something similar to list comprehension in dict?

Simon Brunning simon at brunningonline.net
Fri Nov 20 13:00:53 CET 2009


2009/11/20 Michele Simionato <michele.simionato at gmail.com>:
> Yes, but only in Python 3:
>
>>>> {(i, x) for i, x in enumerate('abc')}
> {(0, 'a'), (1, 'b'), (2, 'c')}

In Python 2.x, you can do:

>>> dict((i, x) for i, x in enumerate('abc'))
{0: 'a', 1: 'b', 2: 'c'}

(Works in 2.5 - I can't remember when generator expressions were introduced.)

-- 
Cheers,
Simon B.



More information about the Python-list mailing list