问题描述
如何在python中从给定的字典中获取所有组合(列出)?
我的输入:
my_dict = {"location_01":"Item_01","location_02":"Item_02","location_03":"Item_03"}
所需的输出:
[{"location_01": "Item_01","location_02": "Item_02","location_03": "Item_03"},{"location_01": "Item_02","location_02": "Item_01",{"location_01": "Item_03","location_03": "Item_01"},{"location_02": "Item_01","location_01": "Item_02",{"location_02": "Item_02","location_01": "Item_01",{"location_02": "Item_03",{"location_03": "Item_01","location_01": "Item_03"},{"location_03": "Item_02","location_01": "Item_02"},{"location_03": "Item_03","location_01": "Item_01"}]
解决方法
您对 itertools
的想法是正确的,但您想要排列而不是组合:
from itertools import permutations
lst = [{k: my_dict[k] for k in l} for l in permutations(my_dict)]
>>> lst
[{'location_01': 'Item_01','location_02': 'Item_02','location_03': 'Item_03'},{'location_01': 'Item_01','location_03': 'Item_03','location_02': 'Item_02'},{'location_02': 'Item_02','location_01': 'Item_01','location_01': 'Item_01'},{'location_03': 'Item_03','location_01': 'Item_01'}]
编辑:
如果您想要所有值的排列,以便生成的字典都不同,请使用:
lst = [{k:v for k,v in zip(my_dict,vals)} for vals in permutations(my_dict.values())]
>>> lst
[{'location_01': 'Item_01','location_02': 'Item_03','location_03': 'Item_02'},{'location_01': 'Item_02','location_02': 'Item_01','location_03': 'Item_01'},{'location_01': 'Item_03','location_03': 'Item_01'}]
,
试试permutations
import itertools
d={"location_01":"Item_01","location_02":"Item_02","location_03":"Item_03"}
x=[dict(zip(d,v)) for v in itertools.permutations(d.values(),3)]
for i in x:
print(i)