Home > Software design >  Python dict of lists full join
Python dict of lists full join

Time:02-12

I have a dict with list values, like this:

d = {'number': [1, 2], 'letter': ['a', 'b']}

I need to full join those lists, so I do:

keys = list(d.keys())

r = [
    {keys[0]: v1, keys[1]: v2}
    for v1 in d[keys[0]]
    for v2 in d[keys[1]]
]

This delivers the desired result:

[{'number': 1, 'letter': 'a'}, {'number': 1, 'letter': 'b'}, {'number': 2, 'letter': 'a'}, {'number': 2, 'letter': 'b'}]

How do I scale this solution for a case of 3 or more lists? For example if I need to process a dict of 3 lists:

d = {'number': [1, 2], 'letter': ['a', 'b'], 'sign': ['!', '.']}

How to do this in case I don't know the number of lists inside the dict?

CodePudding user response:

IIUC, use itertools.product like this:

>>> from itertools import product
>>> d = {'number': [1, 2], 'letter': ['a', 'b']}
>>> [dict(zip(d, vs)) for vs in product(*d.values())]
[{'number': 1, 'letter': 'a'}, {'number': 1, 'letter': 'b'}, {'number': 2, 'letter': 'a'}, {'number': 2, 'letter': 'b'}]
  • Related