I have two dictionaries Dict1 and Dict2. The values for every key in Dict1 are lists as shown below:
Dict1 = { D1:[ C1, C2], D2: [C1], D3: [C2, C3], D4: [C3]}
But Dict2 consists of keys which are values from Dict1. The values in Dict 2 are lists consisting of tuples as shown below.
Dict2 = { C1: [ (W1, 1 ), (W2, 5), (W3, 4) ], C2: [ (W3, 2), (W4, 6) , (W5, 7) ], C3:[ (W6,0),( W1,4), ( W2, 8)], C4: [(W7,3 ),(W8, 8)])
I am interested in creating Dict3 that consists of keys from Dict1 with values from first elements of the tuples in the list which are values in Dict2 as shown below.You can ignore the second elements of the tuple.
For example C1 has [W1, W2, W3] as first elements and C2 has [W3, W4, W5] as first elements. Since D1 in Dict1 is D1: [C1, C2], I would like to combine the list of C1 and C2 as [W1, W2, W3, W4, W5].
So the final desired output is:
Dict3= { D1: [W1, W2, W3, W4, W5], D2:[W1, W2, W3], D3:[W3, W4, W5, W6, W1, W2 ] }
How do I get Dict 3 from Dict1 and Dict2?
here is my code:
Dict1 = { 'D1':[ 'C1', 'C2'], 'D2': ['C1'], 'D3': ['C2', 'C3'], 'D4': ['C3']}
Dict2 = { 'C1': [ ('W1', 1 ), ('W2', 5), ('W3', 4) ], 'C2': [ ('W3', 2), ('W4', 6) , ('W5', 7) ], 'C3':[ ('W6',0),( 'W1',4), ( 'W2', 8)], 'C4': [('W7',3 ),('W8', 8)]}
for d, c_list in Dict1.items():
for c in c_list:
for cw, w_tup_list in Dict2.items():
if (c == cw):
w_list = []
for w_tup in w_tup_list:
w_list.append(w_tup[0])
print (d, w_list)
The current output I get is
D1 ['W1', 'W2', 'W3']
D1 ['W3', 'W4', 'W5']
D2 ['W1', 'W2', 'W3']
D3 ['W3', 'W4', 'W5']
D3 ['W6', 'W1', 'W2']
D4 ['W6', 'W1', 'W2']
My desired output should be dictionary like:
Dict3 = { 'D1':['W1', 'W2', 'W3', 'W4', 'W5'], 'D2': ['W1', 'W2', 'W3'], 'D3': ['W3', 'W4', 'W5', 'W6', 'W1', 'W2' ], 'D4': ['W6', 'W1', 'W2']}