Replace the elements and use the collections.defaultdict default list s values:
from itertools import chain from collections import defaultdict di = defaultdict(list) for key, value in chain(zip(listanum, lista), zip(listbnum, listb)): di[key].append(value)
I used chain to simplify the loop for both sets of key-value pairs; this works in both Python 2 and 3. If this is just Python 2 code, you can use + to combine the two lists.
Output from pprint and switching to a regular dict to simplify printing:
>>> pprint(dict(di)) {1: [['l', 'k'], ['a', 'k']], 2: [['e', '3']], 3: [['c', 'k'], ['c', 'm']], 4: [['x', 'i'], ['v', 'f']], 5: [['d', 'f']]}
This does not create empty lists for the second set; if you have empty lists, you are limited to creating two separate dictionaries and then merging them:
dicta = dict(zip(listanum, lista)) dictb = dict(zip(listbnum, listb)) di = {k: [dicta.get(k, []), dictb.get(k, [])] for k in dicta.viewkeys() | dictb.viewkeys()}
for Python 2, for Python 3 use .keys() instead of .viewkeys() to create:
>>> pprint(di) {1: [['l', 'k'], ['a', 'k']], 2: [['e', '3'], []], 3: [['c', 'k'], ['c', 'm']], 4: [['x', 'i'], ['v', 'f']], 5: [['d', 'f'], []]}
In particular, for your code, you confuse i (the index in lista ) with pos :
if i in listbnum: di[pos][1].append(listb[i])
For i = 4 , i in listbnum is True , but listb[4] does not exist. Your code also tried adding lists from lista and listb , which would not lead to the correct output.
Modify your version a listb using a separate loop for listb / listbnum :
di = {} for i, pos in enumerate(listanum): if pos not in di: di[pos] = [[],[]] di[pos][0][:] = lista[i] for i, pos in enumerate(listbnum): di[pos][1][:] = listb[i]