Is there something similar to list comprehension in dict?

Paul Rudin paul.nospam at rudin.co.uk
Fri Nov 20 04:29:47 EST 2009


Patrick Sabin <patrick.just4fun at gmail.com> writes:

> Peng Yu wrote:
>> I'm wondering if there is something similar to list comprehension for
>> dict (please see the example code below).
>
> Do you mean something like this:
>
>>>> {i:i+1 for i in [1,2,3,4]}
> {1: 2, 2: 3, 3: 4, 4: 5}
>
> This works in python3, but not in python2

Of course in python 2 you can do:

>>> dict((i, i+1) for i in [1,2,3,4])
{1: 2, 2: 3, 3: 4, 4: 5}



More information about the Python-list mailing list