[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

Gary Herron

2/1/2008 6:15:00 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
>
>
This fine example uses list comprehension to build a list of tuples
which is than read by the dict builtin to create a dictionary. You can
dispense with the intermediate list if you use a generator expression
directly as input to the dict builtin. (Requires Python 2.4 or later.)
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}
>>>