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

Cartesian product of dict of lists in Python

I would like to have a Python function cartesian_product which takes a dictionary of lists as input and returns as output a list containing as elements all possible dictionary which can be formed by taking from each list one element. Here would be an example:

Calling

cartesian_product({1: ['a', 'b'], 2: ['c', 'd'], 3: ['e', 'f']})

should return

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

[
  {1: 'a', 2: 'c', 3: 'e'},
  {1: 'a', 2: 'c', 3: 'f'},
  {1: 'a', 2: 'd', 3: 'e'},
  {1: 'a', 2: 'd', 3: 'f'},
  {1: 'b', 2: 'c', 3: 'e'},
  {1: 'b', 2: 'c', 3: 'f'},
  {1: 'b', 2: 'd', 3: 'e'},
  {1: 'b', 2: 'd', 3: 'f'}
]

>Solution :

This should do the trick:

import itertools

def cartesian_product(d):
    return [dict(zip(d, p)) for p in itertools.product(*d.values())]

Demo:

>>> d = {1: ['a', 'b'], 2: ['c', 'd'], 3: ['e', 'f']}
>>> from pprint import pp
>>> pp(cartesian_product(d))
[{1: 'a', 2: 'c', 3: 'e'},
 {1: 'a', 2: 'c', 3: 'f'},
 {1: 'a', 2: 'd', 3: 'e'},
 {1: 'a', 2: 'd', 3: 'f'},
 {1: 'b', 2: 'c', 3: 'e'},
 {1: 'b', 2: 'c', 3: 'f'},
 {1: 'b', 2: 'd', 3: 'e'},
 {1: 'b', 2: 'd', 3: 'f'}]
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