Sorting Dropdown Search Results

Its easy to sort options in dropdowns

rc.Column(
    width=3,
    children=[
        html.Strong("Benchmark (Excess Return)"),
        dcc.Dropdown(
            id='benchmark-dropdown',
            options=sorted([{'label': benchmarks['long_name'][i], 'value': benchmarks['id'][i]}
                            for i in range(0, len(benchmarks))], key=lambda k: k['label']),
            value=292,
            disabled=True,
            clearable=False,
            className="dropdown default minimal"
        )
    ]
),

Pre Search
image

But how do we construct our dropdown properly to sort the search results?

Post Search
image

1 Like

I am also looking for same thing… There should be an option in dash which lets us decide if you want to perform pattern matching with the whole string in dropdown elements or display those results which starts with the searched character in search string.

If you’ve found a way around then please share.

I know this is 3 years old, but the issue still seems to be present. If I type “0” into the dropdown, I’d like the first selected option to respect the order of options I specified (i.e., “30”). Instead, the search results are sorted in ascending value and “10” is selected.

Dropdown_Search

Even if I create a callback to overwrite the built-in search behavior (per Dynamic Options in the dcc.Dropdown docs), the options are sorted in ascending value. In the case of several hundred search results, having to scroll to the bottom to the find the one you want can be tedious.

Any workarounds would be greatly appreciated.

from dash import Dash, html, dcc, Input, Output
from dash.exceptions import PreventUpdate

app = Dash(
    name=__name__,
)

my_options = [30, 20, 10]

app.layout = html.Div(
    [
        dcc.Dropdown(
            id="my-dropdown",
            options=my_options,
            searchable=True,
        ),
    ]
)


# This callback should overwrite the built-in search behavior.
# Instead, the filtered options are sorted by ascending value.
@app.callback(
    Output("my-dropdown", "options"),
    Input("my-dropdown", "search_value"),
)
def custom_search_sort(search_value):
    if not search_value:
        raise PreventUpdate
    return [o for o in my_options if search_value in str(o)]


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