首页 > 解决方案 > 如何访问嵌套字典的内部值

问题描述

我有以下嵌套字典,

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}]

但是,我想将该字典带入以下表单字典,我只想访问valuefrompredictionValues并按原样获取其他键。

预期输出应该是字典

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}]

标签: pythondictionary

解决方案


尝试这个

for d in Data:
    d.update({'value': d.pop('predictionValues')[0].pop('value')})

推荐阅读