提问者:小点点

使用列表值进行词典理解


我想使用字典/列表理解来创建一个字典和多个列表。

以下是我的3个清单:

city_list = ['new york','boston']
times = ['2021-01-01 19:00:00','2021-01-01 20:00:00']
weather_parameters = ['forecastTimeUtc', 'airtemperature', 'condition']

我想创建一个如下所示的词典:

{'new york':[{'forecastTimeUtc': '2021-01-01 20:00:00', 'airTemperature': 0, 'conditionCode': 0}, {'forecastTimeUtc': '2021-01-01 21:00:00', 'airTemperature': 0, 'conditionCode': 0}], 

'boston': [{'forecastTimeUtc': '2021-01-01 20:00:00', 'airTemperature': 0, 'conditionCode': 0}, {'forecastTimeUtc': '2021-01-01 21:00:00', 'airTemperature': 0, 'conditionCode': 0}]}

挑战在于根据“forecastTimeUtc”中的值的多少来增加城市后面的列表。

默认情况下,键“空气温度”和“条件代码”的其他值应该保持为0。


共1个答案

匿名用户

一般来说,当列表理解能够简洁并使代码优雅时,我们会使用它们。我担心想要一个单一的字典理解会混淆代码的读者,我建议为循环构建多个嵌套。

尽管如此,以下是满足您需求的字典压缩:

{city:[{weather_parameter: (time if weather_parameter == 'forecastTimeUtc' else 0) for weather_parameter in weather_parameters} for time in times] for city in city_list}

逐步过程

没有任何列表理解,代码很重

weather_per_city = {}
for city in city_list:
    params_list = []
    for time in times:
        param_dict = {}
        for weather_parameter in weather_parameters:
            if weather_parameter == 'forecastTimeUtc':
                param_dict[weather_parameter] = time
            else:    
                param_dict[weather_parameter] = 0
        params_list.append(param_dict)
    weather_per_city[city] = params_list

仍然没有列表理解,但使用三元运算符开始简化

weather_per_city = {}
for city in city_list:
    params_list = []
    for time in times:
        param_dict = {}
        for weather_parameter in weather_parameters:
            param_dict[weather_parameter] = time if weather_parameter == 'forecastTimeUtc' else 0
        params_list.append(param_dict)
    weather_per_city[city] = params_list

第一,词典理解:

weather_per_city = {}
for city in city_list:
    params_list = []
    for time in times:
        param_dict = {weather_parameter:(time if weather_parameter == 'forecastTimeUtc' else 0) for weather_parameter in weather_parameters}
        params_list.append(param_dict)
    weather_per_city[city] = params_list

第二种理解(词典列表):

weather_per_city = {}
for city in city_list:
    params_list = [{weather_parameter:(time if weather_parameter == 'forecastTimeUtc' else 0) for weather_parameter in weather_parameters} for time in times]
    weather_per_city[city] = params_list