[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

RE: dict comprehension

Ryan Ginstrom

2/1/2008 6:06:00 AM

> 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

3 Answers

Paddy

2/1/2008 6:14:00 AM

0

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)

- Paddy.

Paul McGuire

2/1/2008 8:19:00 AM

0

On Feb 1, 12:13 am, Paddy <paddy3...@googlemail.com> wrote:
> 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)
>
> - Paddy.

Why not just

D = dict(zip(keys,values))

??

-- Paul

Bearophile

2/1/2008 10:10:00 AM

0

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