Dictionary from list?

Marcin 'Qrczak' Kowalczyk qrczak at knm.org.pl
Sat Oct 20 15:43:50 EDT 2001


Sat, 20 Oct 2001 14:42:55 -0400, Tim Peters <tim.one at home.com> pisze:

> It's quite handy in Perl!  Picture parsing a simple textual database with
> key + value lines (like, e.g., mail headers).  In Python you can use
> re.findall() to parse them all up in one gulp, but then you're left with a
> flat [k,v,...] list.

findall(pattern, string)
    Return a list of all non-overlapping matches in the string.

    If one or more groups are present in the pattern, return a
    list of groups; this will be a list of tuples if the pattern
    has more than one group.

It seems that it will return [(k,v),(k,v),...], no?

> dictionary() is a constructor in 2.2, and I spent a lot of time worrying
> about what kind of arguments it should take.  I believe a flat [k,v,...]
> list would have been the most useful thing to accept;

I believe in [(k,v),(k,v),...]. This representation of dictionaries
is much easier to iterate over, and much easier to generate with list
comprehensions.

And it's the inverse of d.items().

And IMHO it's more elegant: the list is homogeneous. It fits statically
typed languages too, unlike [k,v,k,v,...] (it's used in Haskell for
example). I'm using it in my little dynamically typed language.

> Everyone's first thought seems to be that dictionary() should accept
> a list of (key, value) tuples -- but there are few core functions
> that produce such a list

Is there any function which produces [k,v,k,v,...]?

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



More information about the Python-list mailing list