Create permutations of a nested dict

Question:

I’m writing a code that should go over reg_lines and create all the permutations for (1) which lines to use with each protocol and (2) what lines to disconnect in order to check some functionality.

reg_lines = {'primary': ['ETH', 'UDP', 'TCP'], 'secondary': ['ETH', 'TCP'], 'private': ['UDP', 'TCP']}

Expected permutations:

1.

use = [{'primary':'ETH'}]
disc = [{'primary':'ETH'}]
use = [{'primary': 'TCP'}]
disc = [{'primary': 'TCP'}]

j.

use = [{'secondary': 'TCP'}]
disc = [{'secondary': 'TCP'}]

i.

use = [{'primary': 'ETH', 'secondary': 'ETH'}
disc = [{'primary': 'ETH'}]

i+1.

use = [{'primary': 'ETH', 'secondary': 'ETH'}]
disc = [{'primary': 'ETH'}]

i+2.

use = [{'primary': 'ETH', 'secondary': 'ETH'}]
disc = [{'primary': 'ETH', 'secondary': 'ETH'}]

n.

use = [{'primary': 'TCP', 'secondary': 'TCP', 'private': 'TCP'}]
disc = [{'primary': 'TCP', 'secondary': 'TCP', 'private': 'TCP'}]
Asked By: alnet

||

Answers:

First, use itertools.combinations to get all the combinations of primary, secondary, and private, and then itertools.product to get the product of those. Then use itertools.combinations again to get all the subsets of those for the disc dictionaries.

from itertools import product, combinations, chain

reg_lines = {'primary': ['ETH', 'UDP', 'TCP'], 'secondary': ['ETH', 'TCP'], 'private': ['UDP', 'TCP']}

def all_combinations(lst):
    return chain(*[combinations(lst, i+1) for i in range(len(lst))])

for comb in all_combinations(reg_lines):
    for prod in product(*(reg_lines[k] for k in comb)):
        use = dict(zip(comb, prod))
        print("use", use)
        for comb2 in all_combinations(comb):
            disc = {k: use[k] for k in comb2}
            print("disc", disc)

Output:

use {'primary': 'ETH'}
disc {'primary': 'ETH'}
use {'primary': 'UDP'}
disc {'primary': 'UDP'}
... many many more ...
use {'primary': 'TCP', 'secondary': 'TCP', 'private': 'TCP'}
disc {'primary': 'TCP'}
disc {'secondary': 'TCP'}
disc {'private': 'TCP'}
disc {'primary': 'TCP', 'secondary': 'TCP'}
disc {'primary': 'TCP', 'private': 'TCP'}
disc {'secondary': 'TCP', 'private': 'TCP'}
disc {'primary': 'TCP', 'secondary': 'TCP', 'private': 'TCP'}
Answered By: tobias_k
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.