Can I build a dictonary with a list-comprehension?

Hans Nowak hnowak at
Mon Sep 3 10:27:03 CEST 2001

>===== Original Message From "Marcin 'Qrczak' Kowalczyk" <qrczak at> 
>Fri, 31 Aug 2001 15:48:05 +0200, spex66 <spex66 at> pisze:
>> dict = {}
>> LIST = [...] #What you want
>> [dict.update({x: 'spam'}) for x in LIST]
>Using list comprehensions when the result is ignored is misleading
>and inefficient. A for loop is better.
>When there is only a single value, insted of update it's simpler to
>use __setitem__.
>In general, where items come in (key,value) pairs, dictionary can be
>built like this:
>dict = {}
>LIST = [...]
>for k, v in LIST:
>    dict[k] = v
>and there is no simple builtin list-comprehension-like syntax in the
>form of an expression (but you can write a function to convert a list
>to a dictionary).

Un an entirely unrelated note, maybe there should be dictionary 
comprehensions, too... :)

{ k,v for k,v in dict if type(v) == type("") }

<ducking for cover>

--Hans Nowak

More information about the Python-list mailing list