๐Ÿš€ Gen 5 of the leading AI app deployment platform launches October 6. Click for the livestream.

Dash&Python. Multilevel hierarchiel menus/filters not working

I have a small data frame with 4 levels. And I would like to create hierarchial menus/filters. I did create dropdown menus for each level. but when i select for example โ€˜Aโ€™ from the first level, I see all possible options in level2. However, based on the small dataframe I should get the options(โ€˜A1โ€™ and โ€˜A2โ€™) which is under โ€˜Aโ€™ level.

My output is as following:

So actually โ€˜B1โ€™, โ€˜B2โ€™ and โ€˜B3โ€™ is not under โ€˜Aโ€™ level. So, it is not as hiearchial menus.

I would really appreciate your helps

The code example is below:

import dash
import dash_core_components as dcc
import pandas as pd
import dash_bootstrap_components as dbc

def data_preprocessing():
    df = pd.DataFrame({'level1': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],'level2': ['A1', 'A1', 'A1', 'A2', 'B1', 'B2', 'B2', 'B3'],
                   'level3': ['A1.1', 'A1.2', 'A1.3', 'A2.1', 'B1.1', 'B2.1', 'B2.2', 'B3.1'],
                   'level4': ['A1.1.1', 'A1.2.1', 'A1.3.1', 'A2.1.1', 'B1.1.1', 'B2.1.1', 'B2.2.1', 'B3.1.1']})
    return df

def dropdown_menu_filters(position, df):
    types = df[position].unique()
    return dcc.Dropdown(id = f'dropdown-{position}',
        options=[{'label': type,'value': type} for type in types], value='all', multi=True)

def create_app(df):
    app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])
    app.layout = dbc.Container([dbc.Row(dbc.Col(['level1']))]+[dbc.Row(dbc.Col([(dropdown_menu_filters('level1', df))]))] +
                           [dbc.Row(dbc.Col(['level2']))]+[dbc.Row(dbc.Col([(dropdown_menu_filters('level2', df))]))] +
                           [dbc.Row(dbc.Col(['level3']))]+[dbc.Row(dbc.Col([(dropdown_menu_filters('level3', df))]))] +
                           [dbc.Row(dbc.Col(['level4']))]+[dbc.Row(dbc.Col([(dropdown_menu_filters('level4', df))]))])
    return app
dataf = data_preprocessing()
app = create_app(dataf)
if __name__ == '__main__':
    app.run_server(debug=True)

ยด