Given a dictionary
{4: {'idx': [45, 177, 181],
'Baggage': array([ 13, 103, 87]),
'infeed_idx': array([1, 3, 3])},
7: {'idx': [62, 105, 173, 174, 186, 57, 74, 102, 115, 164],
'Baggage': array([12, 27, 50, 51, 16, 30, 15, 59, 16, 8]),
'infeed_idx': array([1, 1, 1, 1, 1, 2, 2, 2, 2, 2])},
I would like to create a tuple of idx and infeed_idx (45,1), (177,3).
Expected output
{4: {'idx': [45, 177, 181],
'Baggage': array([ 13, 103, 87]),
'infeed_idx': array([1, 3, 3])},
'tuple_id': [(45,1),(177,3),(177,3)]
7: {'idx': [62, 105, 173, 174, 186, 57, 74, 102, 115, 164],
'Baggage': array([12, 27, 50, 51, 16, 30, 15, 59, 16, 8]),
'infeed_idx': array([1, 1, 1, 1, 1, 2, 2, 2, 2, 2])},
'tuple_id': [(62,1),(105,1),(173,1),(174,1),(186,1),(57,2),(74,2),(102,2),(115,2),(164,2)]
I hope you guys can help!
CodePudding user response:
Let's say dct
is your dictionary:
for k, d in dct.items():
d['tuple_id'] = list(zip(d['idx'], d['infeed_idx']))
CodePudding user response:
di = {4: {'idx': [45, 177, 181],
'Baggage': np.array([ 13, 103, 87]),
'infeed_idx': np.array([1, 3, 3])},
7: {'idx': [62, 105, 173, 174, 186, 57, 74, 102, 115, 164],
'Baggage': np.array([12, 27, 50, 51, 16, 30, 15, 59, 16, 8]),
'infeed_idx': np.array([1, 1, 1, 1, 1, 2, 2, 2, 2, 2])}}
for key, value in di.items():
value['infeed_idx'] = list(zip(value['idx'], value['infeed_idx']))
print(di)
You can get the job done with a simple for loop. I hope it was helpful.
CodePudding user response:
just use zip
function
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
CodePudding user response:
You could try
d = {4: {'idx': [45, 177, 181],
'Baggage': array([ 13, 103, 87]),
'infeed_idx': array([1, 3, 3])},
7: {'idx': [62, 105, 173, 174, 186, 57, 74, 102, 115, 164],
'Baggage': array([12, 27, 50, 51, 16, 30, 15, 59, 16, 8]),
'infeed_idx': array([1, 1, 1, 1, 1, 2, 2, 2, 2, 2])}
}
for k in d:
d[k]["tuple_id"] = list(zip(d[k]['idx'], d[k]['infeed_idx']))