faqts : Computers : Programming : Languages : Python : Snippets : Dictionaries

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

15 of 18 people (83%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

Two lists -> dictionary
Two lists -> dictionary

Jul 5th, 2000 10:03
Nathan Wallace, unknown unknown, Hans Nowak, Snippet 316, Blake Winton


"""
Packages: basic_datatypes.lists;basic_datatypes.dictionaries
"""
"""
>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.  :)
"""
ListA = ['10', '10', '20', '20', '20', '24']
ListB = ['23', '44', '11', '19', '57', '3']
Dict = {}
for i in range(len(ListA)):
    try:
        Dict[ListA[i]].append(ListB[i])
    except KeyError:
        Dict[ListA[i]] = [ListB[i]]
print Dict
"""
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.
Dict = {}
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.
"""