简体   繁体   English

到/来自列表字典的字典列表,但具有所有可能的排列

[英]List of dicts to/from dict of lists, but with all possible permutations

Coming from question number 5558418, suppose I have a dictionary where values are lists:来自问题编号 5558418,假设我有一个字典,其中的值是列表:

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.我认为 itertools 的 product() 可能很方便,但我不太明白。

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?我如何做与上面相同的事情,但保留所有不是列表的值? eg:例如:

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!谢谢!

Make sure every value is a list and then use itertools.product :确保每个值都是一个列表,然后使用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}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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