Home > Mobile >  Convert two dictionaries to a dictionary of dictionaries containing all combinations
Convert two dictionaries to a dictionary of dictionaries containing all combinations

Time:01-15

Problem

I have two dictionaries: a and b

a={'e':[1,2]}
b={'d':[11,22]}

How can I convert them to a dictionary of dictioneries that contains all possible combinations of the lists [1,2] and [11,22]. The expected result should be:

 dic={1:{'e':1,'d':11},
      2:{'e':2,'d':22},
      3:{'e':1,'d':11},
      4:{'e':2,'d':22}}

My attemt:

I can easily get the combinations of two lists or any set of lists using itertools like so:

l=list(itertools.product([1,2],[11,22]))

But I don't know how to proceed from here. Any suggestions?

CodePudding user response:

You almost have it. Just have to create dictionaries by mapping keys to the tuples in l.

keys = list(a.keys())   list(b.keys())
dic = {k: dict(zip(keys, tpl)) for k, tpl in enumerate(l), 1)}

Here's a bit more generalized approach:

(i) First combine the dictionaries:

combined = {**a, **b}

(ii) Find the Cartesian product the list items in combined.values().

(iii) Iterate over outcome from (ii) and create dictionaries with each tuple and the keys in combined.keys():

dic = {k: dict(zip(combined.keys(), tpl)) for k, tpl in enumerate(itertools.product(*combined.values()), 1)}

Output:

{1: {'e': 1, 'd': 11}, 2: {'e': 1, 'd': 22}, 3: {'e': 2, 'd': 11}, 4: {'e': 2, 'd': 22}}

CodePudding user response:

Given l as you calculated it you can use dict comprehension and achieve the required output -

{idx 1 : {'e': item[0], 'd': item[1]} for idx, item in enumerate(l)}

(BTW there is no need to convert the itertools.product result to list)

  •  Tags:  
  • Related