In general, we use list comprehensions when they can be concise and make your code elegant. I am afraid that wanting a single dictionary comprehension will confuse the readers of your code and I would suggest building multiple nested for loops.
Nonetheless, here is a dictionary compression that meets your needs:
{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}
Step-by-step process
Without any list comprehension, the code is pretty heavy
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
Still no list comprehension, but with a ternary operator to start simplifying
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
First dictionary comprehension:
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
And with a second comprehension (dictionary + 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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…