Reputation: 267
I have a dictionary with multiple entries
res = {'status': 'done', 'nextLogId': 'AQAAAXb', 'logs': [{'content': {'service': 't2pipeline', 'tags': ['tag1:value1', 'tag2:value2', 'tag3:value3'], 'timestamp': '2021-01-05T05:25:03.416Z', 'host': 'i-00e17b8e872ec7d05', 'attributes': {'caller': 'psignal/state_machine.go:451', 'ts': 1609824303.416246, 'level': 'warn'}, 'message': 'psignal: Ignoring scte35 segmentation_descriptor (type:Program Start eventID:0 refUTC:Jan 5 05:25:02.387626333): there is an active segment with the same event_id'}, 'id': 'AQAAAXb'}, {'content': {'service': 't2pipeline', 'tags': ['tag1:value1', 'tag2:value2', 'tag3:value3'], 'timestamp': '2021-01-05T05:25:03.416Z', 'host': 'i-00e17b8e872ec7d05', 'attributes': {'caller': 'psignal/state_machine.go:713', 't2': {'scte35': {'event_id': 0, 'event_ptr': '0xc009f32b40', 'seg_type_id': 16}}, 'ts': 1609824303.4161847, 'level': 'info'}, 'message': 'psignal: scte35 segdesc eventID:0 type:Program Start'}, 'id': 'AQAAAXb'}], 'requestId': 'OVZRd3hv'}
I am trying to create a new dictionary with certain key values including timestamp and message only. I do this in a loop but only the last iteration is present in the dictionary.
new_dict = {}
for i in range(len(res['logs'])):
new_dict['timestamp'] = res['logs'][i]['content']['timestamp']
new_dict['message'] = res['logs'][i]['content']['message']
When I print outside the loop I see only the last entry
print(new_dict)
This is the result
{'timestamp': '2021-01-05T05:25:03.416Z', 'message': 'psignal: scte35 segdesc eventID:0 type:Program Start'}
How do I make it so the new dictionary is updated with both entries. I tried dict.update()
but to no avail.
Upvotes: 0
Views: 46
Reputation: 1173
You need a list:
list_of_dict = []
for i in range(len(res['logs'])):
new_dict = {}
new_dict['timestamp'] = res['logs'][i]['content']['timestamp']
new_dict['message'] = res['logs'][i]['content']['message']
list_of_dict.append(new_dict)
Upvotes: 1