Skip to content Skip to sidebar Skip to footer

Python: From Lists, Build Dict With Key:value Ratio Not 1:1

Pardon me for not finding a better title. Say I have two lists: list1 = ['123', '123', '123', '456'] list2 = ['0123', 'a123', '1234', 'null'] which describe a mapping (see this qu

Solution 1:

from collections import defaultdict

dd = defaultdict(list)
for key, val in zip(list1, list2):
    dd[key].append(val)

Solution 2:

defaultdict() is your friend:

>>> from collections import defaultdict
>>> result = defaultdict(tuple)
>>> for key, value in zip(list1, list2):
...    result[key] += (value,)
...

This produces tuples; if lists are fine, use Jon Clement's variation of the same technique.


Solution 3:

>>> from collections import defaultdict
>>> list1 = ["123", "123", "123", "456"]
>>> list2 = ["0123", "a123", "1234", "null"]
>>> d = defaultdict(list)
>>> for i, key in enumerate(list1):
...     d[key].append(list2[i])
... 
>>> d
defaultdict(<type 'list'>, {'123': ['0123', 'a123', '1234'], '456': ['null']})
>>>

Solution 4:

And a non-defaultdict solution:

from itertools import groupby
from operator import itemgetter

dict( (k, tuple(map(itemgetter(1), v))) for k, v in groupby(sorted(zip(list1,list2)), itemgetter(0)))

Post a Comment for "Python: From Lists, Build Dict With Key:value Ratio Not 1:1"