[英]How do I get all the permutations selecting one item from each value list in a dictionary?
朋友,基本上,我想听一听:
fruit_dict = {'oranges':['big','small'],'apples':['green','yellow','red']}
通过在不同键的所有值之间进行所有可能的排列来获得以下词典列表:
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'}
]
怎么做? 太感谢了!
您要寻找的不是排列,而是笛卡尔乘积 。 可以将其视为嵌套循环。
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)]
然后,您只需要使用现有键和产品中的每个项目来创建新词典。
使用itertools.product()
:
In [94]: dic = {'oranges':['big','small'],'apples':['green','yellow','red']}
In [95]: sort_values=[x[1] for x in sorted(dic.items())] #sorted values based on keys
In [96]: [dict(zip(sorted(dic.keys()),x)) for x in product(*sort_values)]
Out[96]:
[{'apples': 'green', 'oranges': 'big'},
{'apples': 'green', 'oranges': 'small'},
{'apples': 'yellow', 'oranges': 'big'},
{'apples': 'yellow', 'oranges': 'small'},
{'apples': 'red', 'oranges': 'big'},
{'apples': 'red', 'oranges': 'small'}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.