从另一个字典的特定值创建新的 Python 字典

时间:2021-01-12 23:53:42

标签: python python-3.x dictionary for-loop

我有一个包含多个条目的字典

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() 但无济于事。

1 个答案:

答案 0 :(得分:1)

你需要一个列表:

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)
相关问题