Tuple comprehension
Tim Peters
tim.one at comcast.net
Thu Apr 11 11:49:03 EDT 2002
[brueckd at tbye.com]
> ...
> I'd *love* to have dictionary comprehensions!
Try this on for size:
>>> dict([(i, i**2) for i in range(10)])
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
>>>
That is, 2.2 dict() accepts an iterable object producing iterable objects
each producing two values. A list of 2-tuples is one instance of that, and
one particularly easy to create with a listcomp. More possibilities open if
you ponder other kinds of iterable objects; e.g.,
>>> def squarepairs(n):
... for i in range(n):
... yield i, i**2
...
>>> dict(squarepairs(10))
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
>>>
is one way to get the same end result without building a list in one gulp
first.
More information about the Python-list
mailing list