Home > Back-end >  How to create new dictionary from multiple dictionaries when values from one dictionary are keys in
How to create new dictionary from multiple dictionaries when values from one dictionary are keys in

Time:01-26

I have 3 dictionaries from which I want to construct a new dictionary.

dict1 = {'k1' : ('v1', 'v2'), 'k2' : ('v3', 'v4'), 'k3' : ('v5', 'v6')}

Each first value in the tuples in dict1 is a key in dict2.

dict2 = {'v1' : ('x1', 'y1', 'z1'), 'v3' : ('x3', 'y3', 'z3'), 'v5': ('x5', 'y5', 'z5'),}

Each second value in the tuples in dict1 is a key in dict3.

dict3 = {'v2' : ('x2', 'y2', 'z2'), 'v4' : ('x4', 'y4', 'z4'), 'v6' : ('x6', 'y6', 'z6')}

The new dictionary has:

  • new defined keys a formatted string like ‘q{i}’.
  • the values of the keys from dict2 and dict3 (which where in the same tuple in dict1), stored together in a tuple.

dict4 = { 'q1' : ('x1', 'y1', 'z1', 'x2', 'y2', 'z2'), 'q2' : ('x3', 'y3', 'z3', 'x4', 'y4', 'z4'), 'q3' : ('x5', 'y5', 'z5', 'x6', 'y6', 'z6')}

After trying to implement the offered solution, I became aware that my discription of the problem needed more information.

The variables k1, k2,k3,…… are formatted strings in the form of k{j}.

The variables v1, V2, v3, …… are also formatted strings of the form v{a}.

As mentioned earlier the same is valid for the variable q1, q2, q3, … which have the form q{i}.

The variables x, y, z are all floats in the dictionaries.

CodePudding user response:

You can do it in one line:

output = {key: dict2[v1]   dict3[v2] for key, (v1, v2) in dict1.items()}

Since we don't know what are the new keys, I used the original dict1 keys as keys for the new dict4.

CodePudding user response:

Building on @Bharel's excellent answer, you can wrap dict1.values() in enumerate to be able to get the desired key names:

dict4 = {f'q{i}': dict2[v1]   dict3[v2] for i, (v1, v2) in enumerate(dict1.values(), 1)}

Output:

{'q1': ('x1', 'y1', 'z1', 'x2', 'y2', 'z2'),
 'q2': ('x3', 'y3', 'z3', 'x4', 'y4', 'z4'),
 'q3': ('x5', 'y5', 'z5', 'x6', 'y6', 'z6')}
  •  Tags:  
  • Related