简体   繁体   中英

How to dynamically set a default value in a dcc.Dropdown when options come from a callback?

Here is a minimal example of a Dash app code (app.py):

# Libraries
import csv
import pandas as pd
import dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output, State

# CSV files generation

row_list = [
    ["SN", "Name", "Quotes"],
    [1, "Buddha", "What we think we become"],
    [2, "Mark Twain", "Never regret anything that made you smile"],
    [3, "Oscar Wilde", "Be yourself everyone else is already taken"]
]
with open('quotes.csv', 'w', newline='') as file:
    writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC, delimiter=',')
    writer.writerows(row_list)
    
    
import csv
with open('innovators.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(["SN", "Name", "Contribution"])
    writer.writerow([1, "Linus Torvalds", "Linux Kernel"])
    writer.writerow([2, "Tim Berners-Lee", "World Wide Web"])
    writer.writerow([3, "Guido van Rossum", "Python Programming"])


# Style
external_stylesheets = ['assets/style.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)


# Layout
app.layout = html.Div([
    html.Div([  
        dcc.Dropdown(
            id='dropdown_div',
            options=[
                {'label': 'Quotes', 'value': 'quotes.csv'},
                {'label': 'Innovators', 'value': 'innovators.csv'}
            ],
            value='quotes.csv'   
        )
    ]),
    html.Div([
       dcc.Dropdown(
            id='count_div'
       )
    ])
])

# Callback function
@app.callback(
    dash.dependencies.Output('count_div', 'options'),
    [dash.dependencies.Input('dropdown_div', 'value')])
def loadfile(path):
    df = pd.read_csv(path) 
    return [{'label': i, 'value': i} for i in df['Name'].drop_duplicates()]

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

I need the first value of the second Dropdown to be dynamically set as its default value.

In this example, the second dropdown would show

  • Buddha as the default value when Quotes is the selected value of the first dropdown.
  • Linus Torvalds as the default value when Innovators is the selected value of the first dropdown.

The solution is to

  • add an output to the callback function, that sends the default value to the second ddc.Dropdown
  • add the default value to return
# Callback function
@app.callback(
    [dash.dependencies.Output('count_div', 'options'),
    dash.dependencies.Output('count_div', 'value')],
    [dash.dependencies.Input('dropdown_div', 'value')])
def loadfile(path):
    df = pd.read_csv(path) 
    return [{'label': i, 'value': i} for i in df['Name'].drop_duplicates()], df['Name'].drop_duplicates()[0]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM