Search code examples
pythondictionaryfor-looppermutation

How to output permutations for dictionary values


I have a dict with n keys, where let's say n is at least 10. For each key n, it's value is a list of elements and the size of this list is variable. I want to be able to produce all permutations. So the output would be all unique n-length sequences (for the n keys). I will give a simple, contrived example to illustrate the goal. So imagine the dict looks like {'key1': ['a', 'b'], 'key2': ['1', '2'], 'key3' :['*', '!']}. So the output would be (preserving the original order of the keys - [key1, key2, key3]:

['a', '1', '*']
['a', '1', '!']
['a', '2', '*']
['a', '2', '!']
['b', '1', '*']
['b', '1', '!']
['b', '2', '*']
['b', '2', '!']

Again, in my case the number of keys and length of each value would be much greater, but this is just to illustrate the goal. Would appreciate help on how to do this, because normally I use for loops but accounting for a large and variable number of for loops is not feasible. Thanks!


Solution

  • Try this:

    import itertools
    
    d = {'key1': ['a', 'b'], 'key2': ['1', '2'], 'key3' :['*', '!']}
    iter = itertools.product(*d.values())
    

    This gives you an iterator. If you want to expand it into a list, use:

    list(iter)
    

    which produces:

    [('a', '1', '*'),
     ('a', '1', '!'),
     ('a', '2', '*'),
     ('a', '2', '!'),
     ('b', '1', '*'),
     ('b', '1', '!'),
     ('b', '2', '*'),
     ('b', '2', '!')]
    

    Note that the individual entries are tuples, which is probably fine for what you want, but if needed they can easily be converted to lists.