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

2024-05-05 21:30:08 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的词典列表是我的数据集的一个小剪贴。每个列表包含在一个测站测量的数据。然后将每个测量值放入一个单独的字典中。原始数据集包含更多的站和每个站更多的词典

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

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

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

什么是Python式的方法


Tags: 数据number列表字典valueresultstimestamp词典
2条回答
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]}

让我们从您想要得到的内容开始:一个站点字典,其中每个站点的值是一个字典,其中包含来自每个报表的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

相关问题 更多 >