Tuple comprehension

brueckd at tbye.com brueckd at tbye.com
Thu Apr 11 12:52:38 EDT 2002


On Thu, 11 Apr 2002, Tim Peters wrote:

> [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.

Woo-hoo! "Upgrader's delight" is Python's antithesis of "buyer's remorse";
you upgrade to get some new feature only to go back later and discover
additional gems as well.

Thanks for the tip!

-Dave






More information about the Python-list mailing list