Converting to lists into one dictionary

Tim Peters tim_one at email.msn.com
Mon Oct 4 21:43:40 EDT 1999


[Ivan Van Laningham]
> This makes me wonder--why is there no canonical "dict()" built in
> function?

Let's start a rumor:  because Guido doesn't like dicts, and is trying to
remove them from the language <wink>.

> We have "long()", "list()" and so on, but nothing like them
> for dictionaries.  They all know what to do when fed improper input.
>
> Probably, everyone is going to tell me it's too complex an issue, and
> this is of course true to a degree.  Nonetheless, there ought to be a
> straightforward enough way to construct a dictionary from a list, at the
> very least, that it could be built in.

Not me!  It's an easy issue.  It should work on sequences, like so:

dict(seq)
    acts like
def dict(seq):
    i = 0
    d = {}
    while 1:
        try:
            key = seq[i]
        except IndexError:
            break
        try:
            value = seq[i+1]
        except IndexError:
            raise ValueError("dict(seq): seq must have even length")
        d[key] = value
        i = i+2
    return d

dict(seq1, seq2)
    acts like
def(seq1, seq2):
    i = 0
    d = {}
    while 1:
        try:
            key = seq1[i]
        except IndexError:
            break
        try:
            value = seq2[i]
        except IndexError:
            raise ValueError("dict(seq1, seq2): seq2 must be at least "
                             "as long as seq1")
        d[key] = value
        i = i+1
    return d

The bad news is that, despite that these are the correct <wink> definitions,
they have little in common with the suggestions anyone else in sympathy with
this gave.

For example, the original poster wanted None-padding if seq1 and seq2 are of
different lengths, while Greg wanted to raise an exception in that case.
The one above raises an error only if the second sequence is too short (you
can't always ask a sequence for its length in advance, and generating more
from seq2 after seq1 ends-- just to make sure it doesn't have more
elements --is potentially destructive to little good end).

The first version also takes a flat list rather than a list of 2-tuples.
That means it's not an inverse of dict.items(), but I don't care -- anyone
who has slung Perl knows that making a dict from a flat list is 10x more
useful 100x more often (as in the common Perl idiom of making a hash from
the result of a string split).

Implicit in these definitions is also that, in the case of duplicate keys,
"the rightmost one wins".  People *could* reasonably want to raise an error
in that case, or let some other key win, or make a list of all the values
each key maps to.

If no two people can agree on what the functions should do, I'm afraid
that's a good reason not to bless any of them.

otoh-it's-also-a-good-reason-for-guido-to-pick-one-and-say-"live-with-
    it"-to-everyone-else<wink>-ly y'rs  - tim






More information about the Python-list mailing list