Snowman08 Snowman08 - 3 months ago 8
Python Question

How to combine two list in python and match the value with the same key

Question how can I combine these two list and use alist as keys and blist as values. What I would like to is group the values in blist with there corresponding key so lets say values 3, 4, 2, None, None, 1, 1, 1, 6, 1, 2, 4, 5, 5, 7, 1, 1, 2, 3, 4, 5 should have a key as InnerOD and the remaining
should have a key Outter OD None, 3, 4, 6, 5, 1, 3, 2, 2, 2, 2, 1, 1, 1, 1, 3, 4, 3, 5, 6, 5, 2, 3

so basically I would want it to look like this

{Inner OD: [3, 4, 2, None, None, 1, 1, 1, 6, 1, 2, 4, 5, 5, 7, 1, 1, 2, 3, 4, 5], Outter OD: [None, 3, 4, 6, 5, 1, 3, 2, 2, 2, 2, 1, 1, 1, 1, 3, 4, 3, 5, 6, 5, 2, 3]})


Any help would be greatly appreciated.

alist = [u'Outter OD', u'Outter OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Inner OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD', u'Outter OD']

blist = [3, 4, 2, None, None, 1, 1, 1, 6, 1, 2, 4, 5, 5, 7, 1, 1, 2, 3, 4, 5, 1, None, 3, 4, 6, 5, 1, 3, 2, 2, 2, 2, 1, 1, 1, 1, 3, 4, 3, 5, 6, 5, 2, 3]

Answer

Something like this:

res = {}
for i in range(len(alist)):
    if alist[i] in res:
        res[alist[i]].append(blist[i])
    else:
        res[alist[i]]=[blist[i]]

returns {'Inner OD': [2, None, None, 1, 1, 1, 6, 1, 2, 4, 5, 5, 7, 1, 1, 2, 3, 4, 5, 1, None, 3, 4, 6], 'Outter OD': [3, 4, 5, 1, 3, 2, 2, 2, 2, 1, 1, 1, 1, 3, 4, 3, 5, 6, 5, 2, 3]}

Comments