Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python dict of lists full join

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[{'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?

>Solution :

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'}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading