Matt Ellis
Matt Ellis

Reputation: 162

Using recursion to combine values in a dictionary

I have a dictionary containing lists of varying lengths and I would like a general algorithm to produce the combinations of all the elements within the lists. A piece of example code is given below:

bob = {'a':['a','b','c'],     
   'b':[0],
   'c':['x','y']}


for i in bob['a']:
    for j in bob['b']:
        for k in bob['c']:
            print("%s - %s - %s"%(str(i),str(j),str(k)))

This is the desired output for the particular dictionary 'bob' and it produces the output:

a - 0 - x
a - 0 - y
b - 0 - x
b - 0 - y
c - 0 - x
c - 0 - y

However, I would like a general algorithm. Could I use recursion to generalise this so it can handle dictionaries with an arbitrary number of keys, if so how?

Extra Info: The values corresponding to the keys will always be 1D lists

Upvotes: 2

Views: 59

Answers (2)

fferri
fferri

Reputation: 18950

Use product from itertools, it's very handy:

>>> from itertools import product
>>> for x in product(*[bob[k] for k in ('a', 'b', 'c')]):
...     print(' - '.join(map(str, x)))
...
a - 0 - x
a - 0 - y
b - 0 - x
b - 0 - y
c - 0 - x
c - 0 - y

if the order of bob's keys is not relevant, you can simplify this to:

>>> for x in product(*bob.values()):
...     print(' - '.join(map(str, x)))

Upvotes: 3

wim
wim

Reputation: 362826

The general algorithm is itertools.product:

>>> print(*itertools.product(*bob.values()), sep='\n')
('a', 0, 'x')
('a', 0, 'y')
('b', 0, 'x')
('b', 0, 'y')
('c', 0, 'x')
('c', 0, 'y')

Upvotes: 8

Related Questions