简体   繁体   中英

Setting a Plotly Dash dcc.dropdown value dynamically

Im building a plotly Dash dcc.dropdown list dynamically using :

def BuildOptions(DataFrameSeries, AddAll):  
    OptionList = [{'label': i, 'value': i} for i in DataFrameSeries.unique()]
    if AddAll == 1:       
        OptionList.insert(0,{'label': 'All', 'value': 'All'})          
    return OptionList

it uses unique values in a df series, and inserts 'All' into the options list. I now want to Set the (default) value to 'All' if it exists or the [0] item in the list of K/V pairs.

    html.Div([
            dcc.Dropdown(
                id='Prov_DD',                    
                options=BuildOptions(data.TASKPROVINCE,1),
               # value=data.TASKPROVINCE[0],
               # value=dcc.Dropdown.value[0],
                 value='All'  # this works for those list that have 'All' 
                              # but I want [0] item   
                multi=True
            )],className='two columns'
            ),

Any way of setting the dcc drop down to a certain item in the options list of key value pairs by index?

You should define an options_array. Then use that array to populate the dropdown options and value parameters. Once the array is defined you can select a default value by index from the pre-defined array (options_array).

options_array = BuildOptions(data.TASKPROVINCE,1)
html.Div([
    dcc.Dropdown(
    id='Prov_DD',                    
    options=options_array,
    value=options_array[0],
    multi=True)
  ],
  className='two columns'
),

You won't be able to grab a value from dcc.Dropdown(options=...), because it's not actually instantiated yet.

Plus, at this time I think the only other way to pragmatically update dcc.Dropdown is by using callbacks.

Just define the array first.

you can as well achieve this without creating a function. i will use your for as an example to show you how it did worked for me.

    OptionList = [{'label': i, 'value': i} for i in DataFrameSeries.unique()]
    OptionList.insert(0,{'label': 'All', 'value': 'All'}

then in your dropdown component, just say options = optionList like this:

html.Div([
    dcc.Dropdown(
    id='all',                    
    options=optionList,
    value=optionList[0],
    multi=True)
  ]
)

see the results of my own below: 'ALL REGIONS' wasn't on my dataframe. enter image description here

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