【发布时间】:2021-04-17 23:35:28
【问题描述】:
我有一本包含多个条目的字典
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(),但无济于事。
【问题讨论】:
标签: python python-3.x dictionary for-loop