Can I build a dictonary with a list-comprehension?
Roman Suzi
rnd at onego.ru
Mon Sep 3 04:39:59 EDT 2001
On Mon, 3 Sep 2001, Hans Nowak wrote:
> >===== Original Message From "Marcin 'Qrczak' Kowalczyk" <qrczak at knm.org.pl>
> =====
> >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).
>
> Un an entirely unrelated note, maybe there should be dictionary
> comprehensions, too... :)
>
> { k,v for k,v in dict if type(v) == type("") }
Maybe:
{k: v for k,v in dict if type(v) == type("")}
>
> <ducking for cover>
>
> --Hans Nowak
>
>
>
Sincerely yours, Roman A.Suzi
--
- Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru -
More information about the Python-list
mailing list