Question

Okay so I've a Dictionary in Python like this:

dict={'a':'','b':'2','c':'3'}

How do you get an output like this:

[['a','b','c'],
['a','2','c'],
['a','b','3'],
['a','2','3']]

In this result, the original position of the elements don't change but they are simply replaced by their respective meanings in the dictionary. We get a list of lists with different combinations of the elements.

Is this possible? How do I do this? Please help.

Was it helpful?

Solution

Dictionaries aren't ordered, so there is no "original position of the elements". That said, I think you can use itertools.product to generate all the possibilities:

>>> from itertools import product
>>> d = {'a':'','b':'2','c':'3'}
>>> poss = [(k,v) if v else (k,) for k,v in d.items()]
>>> list(product(*poss))
[('a', 'c', 'b'), ('a', 'c', '2'), ('a', '3', 'b'), ('a', '3', '2')]

where poss describes all the choices you want to choose between for each term:

>>> poss
[('a',), ('c', '3'), ('b', '2')]

You could sort by the order of the keys, I guess:

>>> poss = [(k,v) if v else (k,) for k,v in sorted(d.items())]
>>> list(product(*poss))
[('a', 'b', 'c'), ('a', 'b', '3'), ('a', '2', 'c'), ('a', '2', '3')]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top