Can I build a dictonary with a list-comprehension?

Marcin 'Qrczak' Kowalczyk qrczak at knm.org.pl
Mon Sep 3 03:17:13 EDT 2001


Fri, 31 Aug 2001 15:48:05 +0200, spex66 <spex66 at web.de> 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).

-- 
 __("<  Marcin Kowalczyk * qrczak at knm.org.pl http://qrczak.ids.net.pl/
 \__/
  ^^                      SYGNATURA ZASTĘPCZA
QRCZAK



More information about the Python-list mailing list