我有一本有多个条目的字典
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'}
我正在尝试使用某些特定的键值(包括时间戳和消息)来创建新字典。我循环执行此操作,但是字典中仅存在最后一次迭代。
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']
在循环外打印时,我只能看到最后一个条目
print(new_dict)
这是结果 {'timestamp': '2021-01-05T05:25:03.416Z', 'message': 'psignal: scte35 segdesc eventID:0 type:Program Start'}
如何做到这一点,以使新词典同时更新两个条目。我试过了,dict.update()
但无济于事。
您需要一个列表:
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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句