dict comprehension

Daniel Fetchinson fetchinson at googlemail.com
Fri Feb 1 01:18:35 EST 2008


> > Hi folks,
> >
> > There is a withdrawn PEP about a new syntax for dict comprehension:
> > http://www.python.org/dev/peps/pep-0274/ which says:
> >
> > "Substantially all of its benefits were subsumed by generator
> > expressions coupled with the dict() constructor."
> >
> > What does the author mean here? What's the Preferably One Way (TM) to
> > do something analogous to a dict comprehension?
> >
> See about generator expressions in
> http://www.python.org/doc/2.4/whatsnew/node4.html.
>
> The dict builtin can build a dictionary from a list (or iterator or
> generator creating a list) of tuples.   Put them together and get what
> you might be tempted to call a dictionary comprehension.   For instance:
>
> >>> dict((i,i*i) 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}

Neat!



More information about the Python-list mailing list