dict comprehension

Gary Herron gherron at islandtraining.com
Fri Feb 1 01:14:49 EST 2008


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}
>>>




More information about the Python-list mailing list