我有以下字典:
test = OrderedDict({
"one":1,
"two":2,
"three":3
})
我希望得到以下结果:
{'three':3, 'two':2, 'one':1}
{'three':3, 'one':1, 'two':2}
{'two':2, 'three', 'one':1}
{'two':2, 'one':1, 'three':3}
{'one':1, 'three':3, 'two':2}
{'one':1, 'two':2, 'three':3}
这些是可以使用给定测试字典上的排列生成的所有字典。
现在我只能使用以下内容获得可能排列的元组:
for perm in itertools.permutations(test):
print(perm)
将输出:
('three', 'two', 'one')
('three', 'one', 'two')
('two', 'three', 'one')
('two', 'one', 'three')
('one', 'three', 'two')
('one', 'two', 'three')
如何使用itertools获取带有键/值而不是元组的字典?
编辑: 将测试更改为OrderedDict
答案 0 :(得分:1)
虽然字典没有顺序,但您可以将排列作为元组获取并将其转换为OrderedDict
:
>>> import itertools
>>> import collections
>>> for item in itertools.permutations(test.items()):
... print collections.OrderedDict(item)
...
OrderedDict([('three', 3), ('two', 2), ('one', 1)])
OrderedDict([('three', 3), ('one', 1), ('two', 2)])
OrderedDict([('two', 2), ('three', 3), ('one', 1)])
OrderedDict([('two', 2), ('one', 1), ('three', 3)])
OrderedDict([('one', 1), ('three', 3), ('two', 2)])
OrderedDict([('one', 1), ('two', 2), ('three', 3)])