Using recursion to combine values ​​in a dictionary

I have a dictionary containing lists of various lengths, and I would like the general algorithm to produce combinations of all the elements in the lists. An example code example is shown 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 result for a particular bob dictionary, and it outputs the result:

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

However, I need a general algorithm. Can I use recursion to generalize this so that it can handle dictionaries with an arbitrary number of keys, if so, how?

Additional information: the values ​​corresponding to the keys will always be 1D lists

+4
source share
2 answers

General algorithm 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')
+8
source

Use the product from itertools, it is very convenient:

>>> 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 the keys bobdoesn't matter, you can simplify this:

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

Source: https://habr.com/ru/post/1696225/


All Articles