Coming from question number 5558418, suppose I have a dictionary where values are lists:
DL = {'a': [0, 1], 'b': [2, 3]}
And I want to convert it to a list of dictionaries, but with all possible permutations. That is, instead of
LD = [{'a': 0, 'b': 2}, {'a': 1, 'b': 3}]
I now want:
LD = [{'a': 0, 'b': 2}, {'a': 0, 'b': 3}, {'a': 1, 'b': 2}, {'a': 1, 'b': 3}]
How can I do that? I think itertools' product() may be handy but I can't quite figure it out.
Bonus: In my actual problem, some values are not lists. How can I do the same as above, but preserving all values that are not lists? e.g.:
D = {'a': [0, 1], 'b': [2, 3], 'c':7, 'd':9}
Becomes:
L = [{'a': 0, 'b': 2, 'c':7, 'd':9}, {'a': 0, 'b': 3, 'c':7, 'd':9}}, {'a': 1, 'b': 2, 'c':7, 'd':9}}, {'a': 1, 'b': 3, 'c':7, 'd':9}}]
Thanks!
CodePudding user response:
Make sure every value is a list and then use itertools.product
:
from itertools import product
# DL = {'a': [0, 1], 'b': [2, 3]}
D = {'a': [0, 1], 'b': [2, 3], 'c': 7, 'd': 9}
res = [dict(zip(D, p)) for p in product(*[v if isinstance(v, list) else [v] for v in D.values()])]
print(res)
Output
[{'a': 0, 'b': 2, 'c': 7, 'd': 9}, {'a': 0, 'b': 3, 'c': 7, 'd': 9}, {'a': 1, 'b': 2, 'c': 7, 'd': 9}, {'a': 1, 'b': 3, 'c': 7, 'd': 9}]