如何访问嵌套字典的内部值

时间:2020-08-27 08:49:08

标签: python dictionary

我有以下嵌套字典,

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

4 个答案:

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