Dictionary from list?

Tim Peters tim.one at home.com
Sat Oct 20 14:42:55 EDT 2001


[Michael Hudson, on making a dict out of a [key, value, key, value, ...]
 list]
> ...
> I've never found myself needing to do this, but that may be because
> I'm not used to having a convenient way of going from
> [k1,v1,k2,v2,...] to a dict.

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.  In Perl you assign the list to a hash, and you're
done.  Now run this backwards:  since this is so convenient in Perl, Perl
programs often create textual mini-databases in this format, and before you
know it "Python sucks for everything I do" <wink>.  OTOH, in Python I often
maintain textual mini-databases by writing repr(some_dict) to a file, then
reconstruct the dict blazingly fast later via
eval(open('that_file').read()) -- and before you know it Perl sucks for
everything I do.

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; but it had to at least
accept a mapping object, and that's all it accepts (for now).  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
(dict.items(), zip() and some cases of map() are all that pop to mind), so I
had a hard time picturing a good use for that (yet another way to spell
dict.copy() is not a good use).

lost-in-consequences-ly y'rs  - tim





More information about the Python-list mailing list