Novice Question: two lists -> dictionary

Blake Winton bwinton at tor.dhs.org
Wed Apr 14 23:45:55 EDT 1999


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/





More information about the Python-list mailing list