如何从给定的字典中获取所有组合?

问题描述

如何在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)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...