1

朋友们,基本上,我想听听:

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

怎么做?太感谢了!

4

2 回答 2

8

您要寻找的不是排列,而是笛卡尔积。把它想象成一个嵌套循环。

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

然后,您只需使用现有密钥和产品中的每个项目创建一个新字典。

于 2012-12-27T03:04:22.350 回答
0

使用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'}]
于 2012-12-27T03:15:31.063 回答