简体   繁体   中英

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?

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}]

You can try this.

a = [{'a': 1}, {'b': 2}]
b = [{'c': 3}, {'d': 4}]
d = [ {**i, **j} for i in a for j in b ]
print(d) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM