访问字典列表并使用相同的键合并字典

时间:2019-01-27 09:21:37

标签: python list dictionary

下面的词典列表是我的数据集的简短切口。每个列表都包含一个站点上测得的数据。然后将每个测量值放入单独的词典中。原始数据集包含更多的站点,每个站点包含更多的字典。

results =[[{'value': 14.6,'timestamp_measured': '2017-12-31T20:00:00+00:00',
            'station_number': 'NL1','formula': 'PM10'}, 
            {'value': 16.6, 'timestamp_measured': '2017-12-31T21:00:00+00:00',
             'station_number': 'NL1', 'formula': 'PM10'}],
            [{'value': 27.2, 'timestamp_measured': '2017-12-31T20:00:00+00:00',
              'station_number': 'NL2','formula': 'PM10'},
            {'value': 19.0, 'timestamp_measured': '2017-12-31T21:00:00+00:00',
             'station_number': 'NL2','formula': 'PM10'}]] 

我希望每个“ station_number”只有一个字典,而不是每个测量值都有单独的字典,其中包含“公式”和所有测量值的列表:

results = {'station_number': 'NL1', 'formula': 'PM10', 'value': [14.6, 16.6]},
          {'station_number': 'NL2', 'formula':'PM10', 'value': [27.2, 19.0]},

什么是Python方式做到这一点?

2 个答案:

答案 0 :(得分:0)

stations = {}
for lst in results:
    for d in lst:
        if d['station_number'] not in stations:
            stations[d['station_number']] = {
                'formula': d['formula'],
                'timestamp_measured': [], 
                'value': []
            }
        stations[d['station_number']]['timestamp_measured'].append(d['timestamp_measured'])
        stations[d['station_number']]['value'].append(d['value'])

键是站号,因此:

for k, v in stations.items():
    print('{}:\n{}'.format(k, v))

将打印:

NL1:
{'formula': 'PM10', 'timestamp_measured': ['2017-12-31T20:00:00+00:00', '2017-12-31T21:00:00+00:00'], 'value': [14.6, 16.6]}
NL2:
{'formula': 'PM10', 'timestamp_measured': ['2017-12-31T20:00:00+00:00', '2017-12-31T21:00:00+00:00'], 'value': [27.2, 19.0]}

答案 1 :(得分:0)

让我们从您想要获得的内容开始:站点字典,其中每个站点的值是一个字典,其中包含每个报告中value的列表。因此,首先收集常数部分,然后将值收集在列表中:

new_stations = dict()

for station in results:
    # Copy the fixed info
    fixed = station[0]
    name = fixed["station_number"]
    this_station = { "formula": fixed["formula"], 
                     "station_number": name,
                     "value": []
                   }
    # Now collect the values
    for record in station:
        this_station["value"].append(record["value"])

    # Save the station in our main dict
    new_stations[name] = this_station
相关问题