User981636
User981636

Reputation: 3629

Python Dash dropdown with many values

I would like to insert a dropdown menu for an "Age" field in my app going from 0 to 100. However, is there a better way than writing a long dictionary to define the values of the dropdown component? How to avoid the {'label': '1', 'value': '1'}, {'label': '2', 'value': '2'} ... up to 100?

import dash
import dash_html_components as html
import dash_core_components as dcc

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
    dcc.Dropdown(
        id='demo-dropdown',
        options=[
            {'label': '1', 'value': '1'},
            {'label': '2', 'value': '2'},
            {'label': '3', 'value': '3'}
        ],
        value='NYC'
    ),
    html.Div(id='dd-output-container')
])


@app.callback(
    dash.dependencies.Output('dd-output-container', 'children'),
    [dash.dependencies.Input('demo-dropdown', 'value')])
def update_output(value):
    return 'Your age is "{}"'.format(value)


if __name__ == '__main__':
    app.run_server(debug=True)

Upvotes: 0

Views: 715

Answers (1)

Igna
Igna

Reputation: 1127

You can have a list comprehension to generate the list of dictionaries like so:

options=[{"label":str(i),"value":str(i)} for i in range(0,101)]

Upvotes: 1

Related Questions