Compute the product of 3 dictionaries and concatenate keys and values

The function that will do the job is itertools.product. First, here is how you can print out the product dict1 x dict2 x dict3:

for t in product(dict1.items(), dict2.items(), dict3.items()): 
     k, v = zip(*t) 
     print("_".join(k), "-", " and ".join(v))   

Output:

A_B_F - a and b and f
A_B_G - a and b and g
A_C_F - a and c and f
A_C_G - a and c and g
A_D_F - a and d and f
A_D_G - a and d and g
A_E_F - a and e and f
A_E_G - a and e and g

Now, just populate a result dictionary:

result = {}
for t in product(dict1.items(), dict2.items(), dict3.items()): 
     k, v = zip(*t) 
     result["_".join(k)] = " and ".join(v)

You can now add to this dictionary the dict1 x dict2 and dict1 x dict3 products, that are even simpler to compute.


Based on @ShadowRanger's comment, here is a complete snippet:

import itertools
import pprint


dict1 = {
  "A": "a"
}

dict2 = {
  "B": "b",
  "C": "c",
  "D": "d",
  "E": "e"
}

dict3 = {
  "F": "f",
  "G": "g"
}


result = {}
for dicts in ((dict1, dict2), (dict1, dict3), (dict1, dict2, dict3)):
    for t in itertools.product(*(d.items() for d in dicts)):
        k, v = zip(*t)
        result["_".join(k)] = " and ".join(v)

pprint.pprint(result)

Output:

{'A_B': 'a and b',
 'A_B_F': 'a and b and f',
 'A_B_G': 'a and b and g',
 'A_C': 'a and c',
 'A_C_F': 'a and c and f',
 'A_C_G': 'a and c and g',
 'A_D': 'a and d',
 'A_D_F': 'a and d and f',
 'A_D_G': 'a and d and g',
 'A_E': 'a and e',
 'A_E_F': 'a and e and f',
 'A_E_G': 'a and e and g',
 'A_F': 'a and f',
 'A_G': 'a and g'}

Tags:

Python