Tor*_*den 1 python dictionary list permutation
朋友,基本上,我想采取一个字典:
fruit_dict = {'oranges':['big','small'],'apples':['green','yellow','red']}
Run Code Online (Sandbox Code Playgroud)
并通过在不同键的所有值之间进行所有可能的排列来获得以下字典列表:
output_list =
[
{'oranges':'big','apples':'green'},
{'oranges':'big','apples':'yellow'},
{'oranges':'big','apples':'red'},
{'oranges':'small','apples':'green'},
{'oranges':'small','apples':'yellow'},
{'oranges':'small','apples':'red'}
]
Run Code Online (Sandbox Code Playgroud)
怎么做?太感谢了!
您正在寻找的不是排列,而是笛卡尔积.可以把它想象成一个嵌套循环.
from itertools import product
fruit_dict = {'oranges':['big','small'],'apples':['green','yellow','red']}
keys, values = zip(*fruit_dict.items())
print [dict(zip(keys, value_list)) for value_list in product(*values)]
Run Code Online (Sandbox Code Playgroud)
然后,您只需使用现有密钥和产品中的每个项目创建一个新字典.