faqts : Computers : Programming : Languages : Python : Snippets : Lists

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

29 of 31 people (94%) answered Yes
Recently 10 of 10 people (100%) answered Yes

Entry

Converting two lists into one dictionary
Converting+two+lists+into+one+dictionary

Jul 15th, 2002 09:49
Michael Chermside, Nathan Wallace, unknown unknown, Hans Nowak, Snippet 232, Tim Peters, Andy Stenger


Quite simple:
>>> keys = [1, 2, 3]
>>> values = ['a', 'b', 'c']
>>> aDict = dict(zip(keys,values))
>>> aDict
{1: 'a', 2: 'b', 3: 'c'}
The answer below here is the old answer, before this feature
was added to the built-in dict object.
----------------------------------------------------------------------
"""
Packages: basic_datatypes.dictionaries
"""
"""
> 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 dict2(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
"""