Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   RE: dict comprehension (http://www.velocityreviews.com/forums/t588740-re-dict-comprehension.html)

 Ryan Ginstrom 02-01-2008 06:06 AM

RE: dict comprehension

> On Behalf Of Daniel Fetchinson
> What does the author mean here? What's the Preferably One Way
> (TM) to do something analogous to a dict comprehension?

I imagine something like this:

>>> keys = "a b c".split()
>>> values = [1, 2, 3]
>>> D = dict([(a, b) for a, b in zip(keys, values)])
>>> D

{'a': 1, 'c': 3, 'b': 2}

Regards,
Ryan Ginstrom

Re: dict comprehension

On Feb 1, 6:06 am, "Ryan Ginstrom" <softw...@ginstrom.com> wrote:
> > On Behalf Of Daniel Fetchinson
> > What does the author mean here? What's the Preferably One Way
> > (TM) to do something analogous to a dict comprehension?

>
> I imagine something like this:
>
> >>> keys = "a b c".split()
> >>> values = [1, 2, 3]
> >>> D = dict([(a, b) for a, b in zip(keys, values)])
> >>> D

>
> {'a': 1, 'c': 3, 'b': 2}
>
> Regards,
> Ryan Ginstrom

Hi Ryan, that uses a list comprehension.
The generator comprehension is:
D = dict((a, b) for a, b in zip(keys, values))

(No square brackets)

 Paul McGuire 02-01-2008 08:19 AM

Re: dict comprehension

> On Feb 1, 6:06 am, "Ryan Ginstrom" <softw...@ginstrom.com> wrote:
>
> > > On Behalf Of Daniel Fetchinson
> > > What does the author mean here? What's the Preferably One Way
> > > (TM) to do something analogous to a dict comprehension?

>
> > I imagine something like this:

>
> > >>> keys = "a b c".split()
> > >>> values = [1, 2, 3]
> > >>> D = dict([(a, b) for a, b in zip(keys, values)])
> > >>> D

>
> > {'a': 1, 'c': 3, 'b': 2}

>
> > Regards,
> > Ryan Ginstrom

>
> Hi Ryan, that uses a list comprehension.
> The generator comprehension is:
> * D = dict((a, b) for a, b in zip(keys, values))
>
> (No square brackets)
>

Why not just

D = dict(zip(keys,values))

??

-- Paul

 bearophileHUGS@lycos.com 02-01-2008 10:09 AM

Re: dict comprehension

Paul McGuire:
> Why not just
> D = dict(zip(keys,values))
> ??

Because this may require less memory:

from itertools import izip
D = dict(izip(keys, values))

:-)

Bear hugs,
bearophile

 All times are GMT. The time now is 03:45 PM.