Search code examples
pythonlist-comprehensiondictionary-comprehension

Cartesian product of two dict in two lists in Python


Here is my code.

>>> a = [{'a': 1}, {'b': 2}]
>>> b = [{'c': 3}, {'d': 4}]

I want to show:

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

Is there a way I can do it only with list/dict comprehension?


Solution

  • A one line, no import solution can consist of a lambda function:

    f = lambda d, c:[c] if not d else [i for k in d[0] for i in f(d[1:], {**c, **k})]
    
    a = [{'a': 1}, {'b': 2}]
    b = [{'c': 3}, {'d': 4}]
    print(f([a, b], {}))
    

    Output:

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

    However, a much cleaner solution can include itertools.product:

    from itertools import product
    result = [{**j, **k} for j, k in product(a, b)]
    

    Output:

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