Black Lives Matter. Please consider donating to Black Girls Code today.

Dash Dropdowns Sharing Same Pool of Values

Hi all,
First post here and I couldn’t find any other forum post similar to this issue so hopefully it’s not a repost.

I have the following block in my layout:

    html.Div([
        html.Div(
            dcc.Dropdown(
                id='test1',
                options=["a", "b", "c", "d"]
            ),
            style={'width': '43%'}
        ),
        html.Div(
            dcc.Dropdown(
                id='test2',
                options=["a", "b", "c", "d"]
            ),
            style={'width': '43%'}
        )
    ], style={'display': 'flex', 'justify-content': 'space-between'})

I would like it so test1 and test2 cannot have the same value. So if you select “a” for test1, it is not available as an option for test2, and vice versa. Is there a simple way to do this?

Thanks in advance!

A callback similar to the following should work for you. Check out the documention online on dash.callback_context as it provides a wealth of info.

@app.callback(
    [dash.dependencies.Output('test1', 'options'),
     dash.dependencies.Output('test2', 'options')],
    [dash.dependencies.Input('test1', 'value'),
     dash.dependencies.Input('test2', 'value')])
def update_dropdowns(value1, value2):
    ctx = dash.callback_context

    if not ctx.triggered:
        # Handle initial firing on page load - do not update dropdown options
        return dash.no_update, dash.no_update

    options1 = ["a", "b", "c", "d"]
    options2 = ["a", "b", "c", "d"]

    if 'test1' in ctx.triggered:
        # Probably should have error check around remove to ensure value1 is in list before attempting to remove it
        return options1, options2.remove(value1)
    elif 'test2' in ctx.triggered:
        return options1.remove(value2), options2
    else:
        # need to ensure all paths have return value
        return dash.no_update, dash.no_update
1 Like