# RE: dict comprehension

Discussion in 'Python' started by Ryan Ginstrom, Feb 1, 2008.

1. ### Ryan GinstromGuest

> 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

Ryan Ginstrom, Feb 1, 2008

On Feb 1, 6:06 am, "Ryan Ginstrom" <> 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)

3. ### Paul McGuireGuest

On Feb 1, 12:13 am, Paddy <> wrote:
> On Feb 1, 6:06 am, "Ryan Ginstrom" <> 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

Paul McGuire, Feb 1, 2008
4. ### Guest

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

, Feb 1, 2008