Dictionary from list?
Huaiyu Zhu
huaiyu at gauss.almadan.ibm.com
Tue Oct 23 15:49:37 EDT 2001
On Tue, 23 Oct 2001 01:21:04 -0400, Tim Peters <tim.one at home.com> wrote:
>There's already a dictionary() constructor in 2.2, and that's not going to
>change (it would be too odd if every scalar and container builtin type had a
>builtin constructor except for dicts). One question is what it should do;
>all it can do in 2.2b1 is basically silly, amounting to yet another way to
>spell "shallow-copy the argument".
There have been several good arguments about why [(k,v), (k,v) ...] is
better than [k, v, k, v, ...]. Here are some more observations:
- I found Perl's hash initialization quite non-intuitive when I was using
Perl two years ago. Most text files put k,v in the same line, and most
regular expression extract them at once. It takes a little bit extra work
to put k,v pairs into a flat array.
- In Python the sequence-of-pairs structure is easily created by d.items(),
re.match.groups and possibly others. It is quite handy for sorting,
filtering and other processings. It is often necessary to put them into a
dictionary afterwards, and a constructor would be helpful.
- Perhaps a pair of functions flatten(x) and collect(x, n) would be useful
when dealing with flat sequences, even when it is not necessarily
associated with dictionaries.
- As to the question of what the constructor should do in borderline cases, is
there a specific reason that it should not behave exactly like this?
def dict(x):
d = {}
for k, v in x: d[k] = v
return d
There is no need to differentiate between tuples, lists, iterators, etc.
Any sequence whose every element is a sequence of length two should work.
Everything else should raise an exception.
- The form of ([k, k, ...], [v, v, ...]) is less frequently used (in my case
anyway) and can be easily converted using zip().
I keep a file utils.py around that include a many little functions like
the above, and I find myself doing "from utils import dict" quite often.
Another function I use is items(x) returning x.items() if x is dictionary,
or [(i,x[i]), ...] if x is sequence. With dict(), items() and zip() I
could write many programs useful for both lists and dicts.
Huaiyu
More information about the Python-list
mailing list