List comprehensions to generate multiple labels

Hi. I have a large dictionary of weather information that I would like to display using dbc.Label(), and what I’m trying to do is iterate over the dictionary with list comprehension to auto generate all the labels in a column. My issue is that I keep getting this error:

The children property of a component is a list of lists, instead of just a list. Check the component that has the following contents, and remove one of the levels of nesting: 

Here’s the code:

@app.callback(Output('weather_page_layout', 'children'), [Input('daily_update_interval', 'n_intervals')])
def updateWeatherPage(input_data):
    with open('weather_data/weather_fc.json', 'r') as f:
        fc_data = json.load(f)

    weather_page = html.Div(
        children=[
            html.H1('Weather Forecast'),
            dbc.Col(
                [[dbc.Label(f"{k} - {v}") for k,v in i.items()] for i in fc_data]
            )
        ]
    )
    return weather_page

What am I doing wrong here? I’d hate to have to manually type out the entire template with when I can easily format the output using a comprehension and just iterate over the data.

As the error suggests, you are passing a list of lists as the children argument of dbc.Col:

[[dbc.Label(f"{k} - {v}") for k,v in i.items()] for i in fc_data]

is going to resolve as:

[
    [dbc.Label(...), dbc.Label(...), ...],
    [dbc.Label(...), dbc.Label(...), ...],
    ...
]

If you want to create only one list with all these dbc.Label components one after the other, you can change your line to the following:

import itertools

# ...

dbc.Col(
    list(itertools.chain.from_iterable(
        [[dbc.Label(f"{k} - {v}") for k,v in i.items()] for i in fc_data]
    )
)

Thank you. I realized it was a nesting issue, but wasn’t sure how to appropriately get the comprehension to play nice. I’ve never used the itertools library so I need to go read the documentation on that now. Seems useful…

If itertools is unfamilar to you, remember that you can just do classic for loops too!

items = []
for i in fc_data:
    for (k, v) in i.items():
         items.append(dbc.Label(f"{k} - {v}"))

app.layout = dbc.Col(items)