我有以下嵌套字典,
Data = [{'seriesId': 'Food and Beverage',
'forecastPoint': '2020-08-26T00:00:00Z',
'rowId': 35,
'timestamp': '2020-08-27T00:00:00.000000Z',
'predictionValues': [{'value': 32.5133330947, 'label': 'Volume (actual)'}],
'forecastDistance': 1,
'prediction': 32.5133330947},
{'seriesId': 'Food and Beverage',
'forecastPoint': '2020-08-26T00:00:00Z',
'rowId': 36,
'timestamp': '2020-08-28T00:00:00.000000Z',
'predictionValues': [{'value': 30.2438893873, 'label': 'Volume (actual)'}],
'forecastDistance': 2,
'prediction': 30.2438893873}]
但是我想将该词典带入以下形式的词典中,我只想从value
访问predictionValues
并获得其他键。
预期输出应为字典
Data = [{'seriesId': 'Food and Beverage',
'forecastPoint': '2020-08-26T00:00:00Z',
'rowId': 35,
'timestamp': '2020-08-27T00:00:00.000000Z',
'value': 32.5133330947,
'forecastDistance': 1,
'prediction': 32.5133330947},
{'seriesId': 'Food and Beverage',
'forecastPoint': '2020-08-26T00:00:00Z',
'rowId': 36,
'timestamp': '2020-08-28T00:00:00.000000Z',
'value': 30.2438893873,
'forecastDistance': 2,
'prediction': 30.2438893873}]
答案 0 :(得分:2)
尝试一下
for d in Data:
d.update({'value': d.pop('predictionValues')[0].pop('value')})
答案 1 :(得分:1)
使用以下内容
for i in range(len(Data)):
Data[i]['predictionValues'] = Data[i]['predictionValues'][0]['value']
答案 2 :(得分:0)
原始字典列表似乎已经包含预测值,因此只需删除预测值条目即可解决问题
FLAG_ACTIVITY_SINGLE_TOP
答案 3 :(得分:0)
使用dict
进行列表理解方面的工作:
[
dict( (key, value)
if not isinstance(value, list)
else ("value", entry[key][0]["value"])
for key, value in entry.items()
)
for entry in Data
]
[{'seriesId': 'Food and Beverage',
'forecastPoint': '2020-08-26T00:00:00Z',
'rowId': 35,
'timestamp': '2020-08-27T00:00:00.000000Z',
'value': 32.5133330947,
'forecastDistance': 1,
'prediction': 32.5133330947},
{'seriesId': 'Food and Beverage',
'forecastPoint': '2020-08-26T00:00:00Z',
'rowId': 36,
'timestamp': '2020-08-28T00:00:00.000000Z',
'value': 30.2438893873,
'forecastDistance': 2,
'prediction': 30.2438893873}]