From: bwinton at tor.dhs.org (Blake Winton)
Date: Thu, 15 Apr 1999 03:45:55 GMT
Subject: Novice Question: two lists -> dictionary
References: <7f3j1v$f6j$1@nnrp1.dejanews.com>
Message-ID: <slrn7hakos.vsv.bwinton@tor.dhs.org>
Content-Length: 1494
X-UID: 932                                                  

On Thu, 15 Apr, jwtozer at my-dejanews.com <jwtozer at my-dejanews.com> wrote:
>How do I make the members of one list the key of a dictionary and the members
>of a second list the members of list values associated with with those keys?
>
>Given:
>ListA = ['10', '10', '20', '20', '20', '24']
>ListB = ['23', '44', '11', '19', '57', '3']
>
>Desired Result:
>Dict = {'10': ['23','44'],'20': ['11','19','57'], '24': ['3']}
>
>Any help will be much appreciated.

Just off the top of my head, (after some playing around, cause
it's sooo easy to do with Python.  :)

Dict = {}
for i in range(len(ListA)):
    try:
        Dict[ListA[i]].append(ListB[i])
    except KeyError:
        Dict[ListA[i]] = [ListB[i]]

This gives us
Dict = {'24': ['3'], '10': ['23', '44'], '20': ['11', '19', '57']}

I think you could write a sort function of some sort if you really
needed to get the elements in order, but it would probably just
be easier to use:

x = Dict.keys()
x.sort()
for i in x:
    print i, "=", Dict[i]

And I'm sure there's an easier way to do it, as well as a way involving
map and or reduce, but it's been a while since I've programmed
functionally, so I'm not going to try.

# ignore the following code.
def myfunc( key, value ):
    global Dict
    try:
        Dict[key].append(value)
        return "got it"
    except KeyError:
        Dict[key] = [value]
        return "need it"
map( myfunc, ListA, ListB )

Hope this helps,
Blake.

-- 
I speak for PCDocs
http://www.cluetrain.com/





