Snowman08 - 1 year ago 63
Python Question

# Partition list based on elements of another list as keys

How can I combine these two lists and use

`alist`
as keys and
`blist`
as values? What I would like to do is group the values in
`blist`
with the corresponding keys. So let's 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
`'Inner OD'`
as key 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]
``````

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]}`

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download