dict comprehension

Stefan Behnel stefan_ml at behnel.de
Fri Feb 1 12:29:54 EST 2008


Wildemar Wildenburger wrote:
> Arnaud Delobelle wrote:
>>> I believe both set and dict comprehensions will be in 3.0.
>>
>> Python 3.0a1+ (py3k:59330, Dec  4 2007, 18:44:39)
>> [GCC 4.0.1 (Apple Inc. build 5465)] on darwin
>> Type "help", "copyright", "credits" or "license" for more information.
>>>>> {x*x for x in range(10)}
>> {0, 1, 4, 81, 64, 9, 16, 49, 25, 36}
>>>>> {x:x*x for x in range(10)}
>> {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
>>
> OK, not bad. But I don't really see how this is better than the
> generator approach.

It's a literal syntax, just like you would do with a list, i.e. a list
comprehension. Why should you have list comps and no dict comps?


> Also, what is that first thing? A valueless dict (and thus a set)?

It's the literal set syntax added in 3.0. You can write

  {1,2,3}

to get a set() or

  {1:1,2:2}

to get a dict().

Stefan



More information about the Python-list mailing list