Can I build a dictonary with a list-comprehension?

Alex Martelli aleax at aleax.it
Mon Sep 3 11:53:51 EDT 2001


"Marcin 'Qrczak' Kowalczyk" <qrczak at knm.org.pl> wrote in message
news:slrn9p76j7.ga8.qrczak at qrnik.zagroda...
> Mon, 3 Sep 2001 12:39:59 +0400 (MSD), Roman Suzi <rnd at onego.ru> pisze:
>
> > {k: v for k,v in dict if type(v) == type("")}
>
> Although this:
>     dictionary ([(k,v) for k,v in dict.items() if type(v) == str])
> is not as concise, it doesn't require new syntax, just standard
> library support.
>
> In Python-2.2a1 there is already a buildin variable 'dictionary'
> bound to the dictionary type which also acts as a function. But
> it currently just ignores its parameters. I don't know the status
> of the discussion about how its parameters should look like.

I don't know either, but having it accept a sequence of pairs
(to be taken as key/value) would seem VERY natural -- "how do
I build a dictionary from a sequence of pairs" IS a reasonably
frequently asked question.  (Another natural would seem to be
to have dictionary accept keyword-arguments [no positional
ones allowed in this case] and return the **kwds dictionary,
but that one's SO easy to self-code it may not be worth it:-).


Alex






More information about the Python-list mailing list