I am trying to make a simple weather app and I am trying to get all icons by list comprehension. I can't find a way to do that and I can't find any solution so if someone know please let me know. here is data that I am getting from web API. I am capable to do it by days for single one but I can't find a way for list comprehensions thanks
my current code:
data = {
'icon': response['data'][0]['weather']['icon'],
'icon2': response['data'][1]['weather']['icon'],
'icon3': response['data'][2]['weather']['icon'],
'icon4': response['data'][3]['weather']['icon'],
}
and i would like to get something like this
data = {
icons = #list comprehension
}
api result
{'data': [{'app_max_temp': 12.2, 'weather': {'icon': 'c01d', 'code': 800, 'description': 'Clear
Sky'}'min_temp': 5,
{ 'app_max_temp': 13.7, 'weather': {'icon':'c01d','code': 800, 'description': 'Clear Sky'},
'min_temp': 5,
{'app_max_temp': 12.1, 'weather': {'icon': 'c02d', 'code': 802, 'description': 'Scattered
clouds'}'min_temp': 8,
{ 'app_max_temp': 11.8, 'weather': {'icon': 'r01d', 'code': 500, 'description':
'Light rain'}, 'min_temp': 6,}
Can you try this:
icons = [row['weather']['icon'] for row in api_result['data']]
If your api result is corrected to:
api_result = {'data':
[{'app_max_temp': 12.2,
'weather': {'icon': 'c01d', 'code': 800, 'description': 'Clear Sky'},
'min_temp': 5},
{ 'app_max_temp': 13.7,
'weather': {'icon':'c01d','code': 800, 'description': 'Clear Sky'},
'min_temp': 5},
{'app_max_temp': 12.1,
'weather': {'icon': 'c02d', 'code': 802, 'description': 'Scattered clouds'},
'min_temp': 8},
{ 'app_max_temp': 11.8,
'weather': {'icon': 'r01d', 'code': 500, 'description': 'Light rain'},
'min_temp': 6,}
]}
then using the enumerate function to assist with naming your keys, you can do something like the following.
data = {f'icon{icon_index}': icon['weather']['icon']
for icon_index, icon in enumerate(api_result['data'], start=1)}
It outputs:
{'icon1': 'c01d', 'icon2': 'c01d', 'icon3': 'c02d', 'icon4': 'r01d'}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.