# How to connect a dropdown menu with a callback to select a column for sum in Dash?

**URL:** <https://community.plotly.com/t/how-to-connect-a-dropdown-menu-with-a-callback-to-select-a-column-for-sum-in-dash/80940>\
**Category:** 📊 Plotly Python\
**Tags:** question\
**Created:** [December 14, 2023, 5:40pm UTC](https://community.plotly.com/t/how-to-connect-a-dropdown-menu-with-a-callback-to-select-a-column-for-sum-in-dash/80940 "2023-12-14T17:40:25Z")\
**Posts on this page:** 13\
**Page:** 1

<div class="post-metadata">

**Author:** ![lauro.teles](https://avatars.discourse-cdn.com/v4/letter/l/eada6e/32.png) [@lauro.teles](https://community.plotly.com/u/lauro.teles)\
**Post date:** [December 14, 2023, 5:40pm UTC](https://community.plotly.com/t/how-to-connect-a-dropdown-menu-with-a-callback-to-select-a-column-for-sum-in-dash/80940/1 "2023-12-14T17:40:25Z")

</div>

1. I’m trying to create a Dash app to analyze some data. The DataFrame I’m using as a base has a few columns with numerical values. I’m attempting to create a dropdown menu where I can select one of these columns, and then sum the selected column.Here is the code I’m working on. (I’m very new to coding, apologize for any silly mistakes and thanks for any help.)

`

```auto

                ``slider_options = ['Janeiro/2020', 'fereiro/2020', 'Março/2020',
                    'Abril/2020', 'Maio/2020', 'junho/2020', 'julho/2020', 'Agosto/2020',
                    'Setembro/2020', 'Outubro/2020', 'Novembro/2020', 'Dezembro/2020',
                    'Janeiro/2021', 'fereiro/2021', 'Março/2021', 'Abril/2021', 'Maio/2021',
                    'junho/2021', 'julho/2021', 'Agosto/2021', 'Setembro/2021',
                    'Outubro/2021', 'Dezembro/2021', 'Novembro/2021', 'fereiro/2022',
                    'Março/2022', 'Abril/2022', 'Maio/2022', 'junho/2022', 'julho/2022',
                    'Agosto/2022', 'Setembro/2022', 'Outubro/2022', 'Novembro/2022',
                    'Dezembro/2022', 'Janeiro/2023', 'fereiro/2023', 'Março/2023',
                    'Abril/2023', 'Maio/2023', 'junho/2023', 'julho/2023', 'Agosto/2023',
                    'Setembro/2023', 'Outubro/2023']
                marks = {i: option for i, option in enumerat
e(slider_options)}

                app = dash.Dash(external_stylesheets = [dbc.themes.SOLAR],suppress_callback_exceptions=True)

                app.layout =html.Div( children=[
                    dbc.Row([
                        dbc.Col([dbc.Card([
                            html.H3('Selecione o período'),
                            dcc.Dropdown(options=marks
                                ,id='slider',
                                ),

                            html.H3('Seleione a corretora'),
                            dcc.Checklist(arquivo_final['Corretora'].value_counts().index,id='corretora'),

                            html.H3('Seleione o estado'),

                            dcc.Checklist(arquivo_final['UF'].value_counts().index,id='estado'),

                            html.H3('Seleione o escritorio'),
                            dcc.Checklist(arquivo_final['Escritorio'].value_counts().index,id='Escritorio')

                @app.callback(
                    Output('pl_total_barra','figure'),

                    [Input('corretora','value'),
                    Input('estado','value'),
                    Input('Escritorio','value'),
                    Input('slider','value')]
                )
                def update_fig(broker,city,office,selected_option):
                    if not broker or not city or not office or not selected_option:
                        return go.Figure()

                    filtro_corretora = arquivo_final[arquivo_final['Corretora'].isin(broker)]
                    filtro_estado = filtro_corretora[filtro_corretora['UF'].isin(city)]
                    filtro_office = filtro_estado[filtro_estado['Escritorio'].isin(office)]

                    if selected_option in marks:
                        selected_colum = marks[selected_option]
                        if selected_colum in filtro_office.columns:
                            value_to_show = filtro_office[selected_colum].sum()

                    fig_pl_total = go.Figure()
                    fig_pl_total.add_trace(go.Indicator(
                        value=value_to_show
                    ))

                    return fig_pl_total

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

                `
                `

```

Instead of summing the column and showing the value, I’m getting this error:

UnboundLocalError: cannot access the local variable ‘value\_to\_show’ where it is not associated with a value.

Traceback (most recent call last): UnboundLocalError: cannot access local variable ‘value\_to\_show’ where it is not associated with a value.

---

<div class="post-metadata">

**Author:** ![AnnMarieW](https://avatars.discourse-cdn.com/v4/letter/a/ec9cab/32.png) [@AnnMarieW](https://community.plotly.com/u/AnnMarieW)\
**Post date:** [December 15, 2023, 1:26am UTC](https://community.plotly.com/t/how-to-connect-a-dropdown-menu-with-a-callback-to-select-a-column-for-sum-in-dash/80940/2 "2023-12-15T01:26:35Z")

</div>

Hi @lauro.teles and welcome to the Dash community 🙂

Could you please provide a minimal example that we can run that recreates the issue?

More information on how to do that here:

> [@How to Get your Questions Answered on the Plotly Forum](https://community.plotly.com/t/how-to-get-your-questions-answered-on-the-plotly-forum/40551/):
>
> Your Plotly community members answer a great majority of the questions posted on the forum. However, responders’ time is limited. To greatly increase your chances of getting your post answered, your questions need to be easy to read and easy to reply to . This post will illustrate exactly how to do that. TL;DR: jump to section WHILE POSTING. BEFORE POSTING: Often, strange or problematic behaviour has been fixed in the most recent version of dash or of plotly so always ensure you’re using th…

---

<div class="post-metadata">

**Author:** ![lauro.teles](https://avatars.discourse-cdn.com/v4/letter/l/eada6e/32.png) [@lauro.teles](https://community.plotly.com/u/lauro.teles)\
**Post date:** [December 15, 2023, 1:12pm UTC](https://community.plotly.com/t/how-to-connect-a-dropdown-menu-with-a-callback-to-select-a-column-for-sum-in-dash/80940/3 "2023-12-15T13:12:13Z")

</div>

> [@AnnMarieW](#):
>
> ion on how

Hello AnnMarieW, thank you for your response, I’ll try to be more clear about the issue.

I have this DataFrame with the following columns:  
I have this df with the following columns:

# Column Non-Null Count Dtype

* * *

0 Corretora 1020 non-null object  
1 Nome\_cliente 1024 non-null object  
2 Conta 1024 non-null object  
3 Escritorio 1020 non-null object  
4 UF 1020 non-null object  
5 Assessor 1020 non-null object  
6 Mesa de Operação 999 non-null object  
7 Status 1020 non-null object  
8 Exeção 1020 non-null object  
9 Inicio da gestão 996 non-null object  
10 Data do distrato 182 non-null object  
11 Carteira 1020 non-null object  
12 Taxa de gestão 1020 non-null object  
13 Benchmark 1014 non-null object  
14 Taxa de performance 1014 non-null object  
15 Janeiro/2020 1024 non-null float64  
16 fereiro/2020 1024 non-null float64  
17 Março/2020 1023 non-null float64  
18 Abril/2020 1023 non-null float64  
19 Maio/2020 1023 non-null float64  
20 junho/2020 1023 non-null float64  
21 julho/2020 1023 non-null float64  
22 Agosto/2020 1024 non-null float64  
23 Setembro/2020 1024 non-null float64  
24 Outubro/2020 1024 non-null float64  
25 Novembro/2020 1024 non-null float64  
26 Dezembro/2020 1024 non-null float64  
27 Janeiro/2021 1024 non-null float64  
28 fereiro/2021 1024 non-null float64  
29 Março/2021 1024 non-null float64  
30 Abril/2021 1024 non-null float64  
31 Maio/2021 1024 non-null float64  
32 junho/2021 1024 non-null float64  
33 julho/2021 1024 non-null float64  
34 Agosto/2021 1024 non-null float64  
35 Setembro/2021 1024 non-null float64  
36 Outubro/2021 1024 non-null float64  
37 Dezembro/2021 1024 non-null float64  
38 Novembro/2021 1024 non-null float64  
39 fereiro/2022 1024 non-null float64  
40 Março/2022 1024 non-null float64  
41 Abril/2022 882 non-null float64  
42 Maio/2022 1024 non-null float64  
43 junho/2022 907 non-null float64  
44 julho/2022 1024 non-null float64  
45 Agosto/2022 1024 non-null float64  
46 Setembro/2022 1024 non-null float64  
47 Outubro/2022 1024 non-null float64  
48 Novembro/2022 1024 non-null float64  
49 Dezembro/2022 1024 non-null float64  
50 Janeiro/2023 1024 non-null float64  
51 fereiro/2023 1024 non-null float64  
52 Março/2023 1023 non-null float64  
53 Abril/2023 1023 non-null float64  
54 Maio/2023 1023 non-null float64  
55 junho/2023 1023 non-null float64  
56 julho/2023 1023 non-null float64  
57 Agosto/2023 1023 non-null float64  
58 Setembro/2023 1023 non-null float64  
59 Outubro/2023 1023 non-null float64

Columns 15 to 59 contain numbers that refer to some financial results of each month. I’m trying to create a dcc dropdown that will select which column will be used to perform operations and show the results in the graph. I’ve also created three other select boxes to filter some additional information. All three select boxes are working. However, the dropdown is not working in a way that allows me to switch columns to see the results from different months. When I try to change the value in the dropdown, I get the following message:

UnboundLocalError: cannot access local variable ‘value\_to\_show’ where it is not associated with a value

## Traceback _(most recent call last)_

> UnboundLocalError: cannot access local variable ‘value\_to\_show’ where it is not associated with a value

This is the Copy/Paste friendly version of the traceback.

UnboundLocalError: cannot access local variable ‘value\_to\_show’

---

<div class="post-metadata">

**Author:** ![adamschroeder](https://sea2.discourse-cdn.com/flex024/user_avatar/community.plotly.com/adamschroeder/32/17280_2.png) [@adamschroeder](https://community.plotly.com/u/adamschroeder)\
**Post date:** [December 15, 2023, 2:35pm UTC](https://community.plotly.com/t/how-to-connect-a-dropdown-menu-with-a-callback-to-select-a-column-for-sum-in-dash/80940/4 "2023-12-15T14:35:05Z")

</div>

hi @lauro.teles  
to follow up on Ann Marie’s comment, can you share your code with us? It would be easier to run your code in our computers and replicated the error you’re getting.

---

<div class="post-metadata">

**Author:** ![lauro.teles](https://avatars.discourse-cdn.com/v4/letter/l/eada6e/32.png) [@lauro.teles](https://community.plotly.com/u/lauro.teles)\
**Post date:** [December 15, 2023, 3:31pm UTC](https://community.plotly.com/t/how-to-connect-a-dropdown-menu-with-a-callback-to-select-a-column-for-sum-in-dash/80940/6 "2023-12-15T15:31:39Z")

</div>

sure @adamschroeder, thanks for your response here follow the hole code:

```auto
import dash
from dash import dcc, html
from dash.dependencies import Input,Output
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
import dash_bootstrap_components as dbc
from dash_bootstrap_templates import load_figure_template
import gunicorn

def le_excel(x,y):
    df_dic = pd.read_excel(x,y)
    return df_dic

btg = le_excel('Controle de Contratos - Atualizado 09.2023.xlsx',1)
guide = le_excel('Controle de Contratos - Atualizado 09.2023.xlsx',2)
genial = le_excel('Controle de Contratos - Atualizado 09.2023.xlsx',3)
agora = le_excel('Controle de Contratos - Atualizado 09.2023.xlsx',4)
orama = le_excel('Controle de Contratos - Atualizado 09.2023.xlsx',5)
novas = le_excel('Controle de Contratos - Atualizado 09.2023.xlsx',6)
arquivo_final = pd.concat([btg,guide,genial,agora,orama]).reset_index()

arquivo_final.drop(columns=['index'],inplace=True)
arquivo_final.drop(988,inplace=True)
linhas_para_retirar =[588,593,983,984,985,986,987,1019,1020,1021,1022,1023,1036,1037,1038,1039,1040,1041,1044,1045,1046,1047,1048]
arquivo_final.drop(linhas_para_retirar,inplace=True)
arquivo_final.drop(1018,inplace=True)
arquivo_final = arquivo_final[[
    'Corretora', 'Nome_cliente', 'Conta', 'Escritorio', 'UF', 'Assessor',
       'Mesa de Operação', 'Status', 'Exeção', 'Inicio da gestão',
       'Data do distrato', 'Carteira', 'Taxa de gestão',
         'Benchmark','Taxa de performance','Janeiro/2020', 'fereiro/2020', 'Março/2020',
       'Abril/2020', 'Maio/2020', 'junho/2020', 'julho/2020', 'Agosto/2020',
       'Setembro/2020', 'Outubro/2020', 'Novembro/2020', 'Dezembro/2020',
       'Janeiro/2021', 'fereiro/2021', 'Março/2021', 'Abril/2021', 'Maio/2021',
       'junho/2021', 'julho/2021', 'Agosto/2021', 'Setembro/2021',
       'Outubro/2021', 'Dezembro/2021', 'Novembro/2021', 'fereiro/2022',
       'Março/2022', 'Abril/2022', 'Maio/2022', 'junho/2022', 'julho/2022',
       'Agosto/2022', 'Setembro/2022', 'Outubro/2022', 'Novembro/2022',
       'Dezembro/2022', 'Janeiro/2023', 'fereiro/2023',
         'Março/2023', 'Abril/2023', 'Maio/2023',
       'junho/2023', 'julho/2023', 'Agosto/2023', 'Setembro/2023',
       'Outubro/2023'
]]

col_fill_na = ['Janeiro/2020', 'fereiro/2020', 'Março/2020',
       'Abril/2020', 'Maio/2020', 'junho/2020', 'julho/2020', 'Agosto/2020',
       'Setembro/2020', 'Outubro/2020', 'Novembro/2020', 'Dezembro/2020',
       'Janeiro/2021', 'fereiro/2021', 'Março/2021', 'Abril/2021', 'Maio/2021',
       'junho/2021', 'julho/2021', 'Agosto/2021', 'Setembro/2021',
       'Outubro/2021', 'Dezembro/2021', 'Novembro/2021', 'fereiro/2022',
       'Março/2022', 'Abril/2022', 'Maio/2022', 'junho/2022', 'julho/2022',
       'Agosto/2022', 'Setembro/2022', 'Outubro/2022', 'Novembro/2022',
       'Dezembro/2022', 'Janeiro/2023', 'fereiro/2023',
         'Março/2023', 'Abril/2023', 'Maio/2023',
       'junho/2023', 'julho/2023', 'Agosto/2023', 'Setembro/2023',
       'Outubro/2023'
]

for col in col_fill_na:
    arquivo_final[col] = arquivo_final[col].fillna(0)

arquivo_final['Inicio da gestão'] = pd.to_datetime(arquivo_final['Inicio da gestão'],errors='coerce')
arquivo_final['Inicio da gestão'] = arquivo_final['Inicio da gestão'].dt.strftime('%d/%m/%Y')    

arquivo_final['Data do distrato'] = pd.to_datetime(arquivo_final['Data do distrato'],errors='coerce')
arquivo_final['Data do distrato'] = arquivo_final['Data do distrato'].dt.strftime('%d/%m/%Y')  
slider_options = ['Janeiro/2020', 'fereiro/2020', 'Março/2020',
       'Abril/2020', 'Maio/2020', 'junho/2020', 'julho/2020', 'Agosto/2020',
       'Setembro/2020', 'Outubro/2020', 'Novembro/2020', 'Dezembro/2020',
       'Janeiro/2021', 'fereiro/2021', 'Março/2021', 'Abril/2021', 'Maio/2021',
       'junho/2021', 'julho/2021', 'Agosto/2021', 'Setembro/2021',
       'Outubro/2021', 'Dezembro/2021', 'Novembro/2021', 'fereiro/2022',
       'Março/2022', 'Abril/2022', 'Maio/2022', 'junho/2022', 'julho/2022',
       'Agosto/2022', 'Setembro/2022', 'Outubro/2022', 'Novembro/2022',
       'Dezembro/2022', 'Janeiro/2023', 'fereiro/2023', 'Março/2023',
       'Abril/2023', 'Maio/2023', 'junho/2023', 'julho/2023', 'Agosto/2023',
       'Setembro/2023', 'Outubro/2023']
marks = {i: option for i, option in enumerate(slider_options)}

app = dash.Dash(external_stylesheets = [dbc.themes.SOLAR],suppress_callback_exceptions=True)

app.layout =html.Div( children=[
    dbc.Row([
        dbc.Col([dbc.Card([
            html.H3('Selecione o período'),
            dcc.Dropdown(options=marks
                ,id='slider',
                ),

            html.H3('Seleione a corretora'),
            dcc.Checklist(arquivo_final['Corretora'].value_counts().index,id='corretora'),

            html.H3('Seleione o estado'),

            dcc.Checklist(arquivo_final['UF'].value_counts().index,id='estado'),

            html.H3('Seleione o escritorio'),
            dcc.Checklist(arquivo_final['Escritorio'].value_counts().index,id='Escritorio')
                                                                                        

        ],style={'height':'98vh',
                     'padding':'5px',
                     'margin':'5px',
                    'font-size':'20px'})],style = {'height':'92vh','margin':'3px'},sm=2),
        dbc.Col([
            dbc.Card([
                html.H4('Dashboard Interativo'),
                        dbc.Row([
                            dbc.Col([
                                dcc.Graph(id='pl_total_barra',config={"displayModeBar":False,"showTips":False}),
                            ],style={'margin':'5px','padding':'5px'},sm=3),
                            dbc.Col([
                                dcc.Graph(id='pl_total_outro',style={'margin-top':'15px'}),
                            ],sm=8)
                        ]),
                        dbc.Row([
                            dbc.Col([
                                dcc.DatePickerRange(id='selecao_de_data',style={'margin-bottom':'20px'}),
                                dbc.Row([
                                    dcc.Graph(id='entrada_clientes')
                                ]),],style={'margin':'5px','padding':'5px'},sm=5),
                                dbc.Col([
                                    dcc.Graph(id='sainda_clientes',style={'margin-top':'65px'})
                                ],style={'margin':'5px','padding':'5px'},sm=5),
                                dbc.Row([
                                    dbc.Col([
                                        dcc.Graph(id='entrada_ecri',style={'margin-top':'5px'}),
                                    ],style={'margin':'5px','padding':'5px'},sm=5),
                                    dbc.Col([
                                        dcc.Graph(id='saida_escri',style={'margin-top':'20px'})
                                    ],style={'margin':'5px','padding':'5px'},sm=5),
                                    dbc.Row([
                                        dbc.Col([
                                            dcc.Graph(id='pl_corretora')
                                        ],style={'margin':'5px','padding':'5px'},sm=5),
                                        dbc.Col([
                                            dcc.Graph(id='contas_por corretora')
                                        ],style={'margin':'5px','padding':'5px'},sm=5),
                                        dbc.Row([
                                            dbc.Col([
                                                dcc.Graph(id='top_assessores')
                                            ],style={'margin':'5px','padding':'5px'},sm=11),
                                            dbc.Row([
                                                dbc.Col([
                                                    dcc.Graph(id='aportes')
                                                ],style={'margin':'5px','padding':'5px'},sm=4),
                                                dbc.Col([
                                                    dcc.Graph(id='resgates')
                                                ],style={'margin':'5px','padding':'5px'},sm=4),
                                                dbc.Col([
                                                    dcc.Graph(id ='apo_res_dif')
                                                ],style={'margin':'5px','padding':'5px'},sm=3),
                                                dbc.Row([
                                                    dbc.Col([
                                                        dcc.Graph(id='top_10_clientes')
                                                    ],style={'margin':'5px','padding':'5px'},sm=5),
                                                    dbc.Col([
                                                        dcc.Graph(id='pl_por_perfil')
                                                    ],style={'margin':'5px','padding':'5px'},sm=5)
                                                    ])
                                                ])
                                                
                                            ])
                                        ])
                                    ])
                                ])

                            
                        ])

            ],style={'height':'98vh',
                     'padding':'5px',
                     'margin':'5px',
                    'font-size':'20px'})
        ]),
        
    ])
@app.callback(
    Output('pl_total_barra','figure'),

    [Input('corretora','value'),
     Input('estado','value'),
     Input('Escritorio','value'),
     Input('slider','value')]
)
def update_fig(broker,city,office,selected_option):
    if not broker or not city or not office or not selected_option:
        return go.Figure()

    filtro_corretora = arquivo_final[arquivo_final['Corretora'].isin(broker)]
    filtro_estado = filtro_corretora[filtro_corretora['UF'].isin(city)]
    filtro_office = filtro_estado[filtro_estado['Escritorio'].isin(office)]
    cols_to_sum = ['Janeiro/2020', 'fereiro/2020', 'Março/2020',
       'Abril/2020', 'Maio/2020', 'junho/2020', 'julho/2020', 'Agosto/2020',
       'Setembro/2020', 'Outubro/2020', 'Novembro/2020', 'Dezembro/2020',
       'Janeiro/2021', 'fereiro/2021', 'Março/2021', 'Abril/2021', 'Maio/2021',
       'junho/2021', 'julho/2021', 'Agosto/2021', 'Setembro/2021',
       'Outubro/2021', 'Dezembro/2021', 'Novembro/2021', 'fereiro/2022',
       'Março/2022', 'Abril/2022', 'Maio/2022', 'junho/2022', 'julho/2022',
       'Agosto/2022', 'Setembro/2022', 'Outubro/2022', 'Novembro/2022',
       'Dezembro/2022', 'Janeiro/2023', 'fereiro/2023',
         'Março/2023', 'Abril/2023', 'Maio/2023',
       'junho/2023', 'julho/2023', 'Agosto/2023', 'Setembro/2023',
       'Outubro/2023']
    
    for col in cols_to_sum:
        arquivo_final[col] = pd.to_numeric(arquivo_final[col],errors='coerce')
    
    
    #value_to_show = filtro_office['Outubro/2023'].sum()

    if selected_option in marks:
        selected_colum = marks[selected_option]
        if selected_colum in filtro_office.columns:
            value_to_show = filtro_office[selected_colum].sum()

    print(arquivo_final.info())

    fig_pl_total = go.Figure()
    fig_pl_total.add_trace(go.Indicator(
        value=value_to_show
    ))

    return fig_pl_total

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

```

---

<div class="post-metadata">

**Author:** ![adamschroeder](https://sea2.discourse-cdn.com/flex024/user_avatar/community.plotly.com/adamschroeder/32/17280_2.png) [@adamschroeder](https://community.plotly.com/u/adamschroeder)\
**Post date:** [December 15, 2023, 7:22pm UTC](https://community.plotly.com/t/how-to-connect-a-dropdown-menu-with-a-callback-to-select-a-column-for-sum-in-dash/80940/7 "2023-12-15T19:22:47Z")

</div>

hi @lauro.teles  
I can’t run this code on my computer because I don’t have the Atualizado 09.2023 excel sheet. That’s why @AnnMarieW suggested you read my post on how to share a minimal reproducible example.

We either need to get your code to fully execute so we can replicate your error, or we start clean by working off a sample data set (`px.data.iris()`, `px.data.gapminder()`, etc.) and try to achieve the same result you’re looking for.

You’re trying to use the callback to select a specific column from the dataframe and sum up the numbers of that column? Did I get that right?

---

<div class="post-metadata">

**Author:** ![lauro.teles](https://avatars.discourse-cdn.com/v4/letter/l/eada6e/32.png) [@lauro.teles](https://community.plotly.com/u/lauro.teles)\
**Post date:** [December 15, 2023, 8:30pm UTC](https://community.plotly.com/t/how-to-connect-a-dropdown-menu-with-a-callback-to-select-a-column-for-sum-in-dash/80940/9 "2023-12-15T20:30:12Z")

</div>

Continuing the discussion from [How to connect a dropdown menu with a callback to select a column for sum in Dash?](https://community.plotly.com/t/how-to-connect-a-dropdown-menu-with-a-callback-to-select-a-column-for-sum-in-dash/80940/7):

Sorry for lack of information @adamschroeder. Yes, that’s exactly it, I’m trying to use the callback to select a specific column from the dataframe and sum up the numbers of that column.  
Also, I made a code that can be replicate.

```auto
import dash
from dash import dcc, html
from dash.dependencies import Input,Output
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
import dash_bootstrap_components as dbc
from dash_bootstrap_templates import load_figure_template
import gunicorn
import streamlit as st
import numpy as np

data = {
    'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva'],
    'Age': [25, 30, 22, 35, 28],
    'Salary': [50000, 60000, 45000, 70000, 55000],
    'Nota1': np.random.randint(1, 10, 5),
    'Nota2': np.random.randint(1, 10, 5),
    'Nota3': np.random.randint(1, 10, 5)
}

df = pd.DataFrame(data)
print(df)

columns_to_use = ['Nota1',
                    'Nota2',
                    'Nota3']

marks = {i: option for i, option in enumerate(columns_to_use)}
app = dash.Dash()
app.layout =html.Div( children=[
    dbc.Row([
        dbc.Col([dbc.Card([
            dcc.Dropdown(
                        options=marks,
                        id='dropdown'),

            dcc.Checklist(df['Name'].value_counts().index,id='name'),

            dcc.Checklist(df['Age'].value_counts().index,id='age'),

            dcc.Checklist(df['Salary'].value_counts().index,id='salary')

    ]),dbc.Col([
        dcc.Graph(id='graph_1',)
    ])
        ])
            ])  
                ])

@app.callback(
    Output('graph_1','figure'),

    [Input('name','value'),
     Input('age','value'),
     Input('salary','value'),
     Input('dropdown','value')]
)
def update_fig(names,ages,salarys,options_dropdown):
    if not names or not ages or not salarys or not options_dropdown:
        return go.Figure()
    

    filter_df_1 = df[df['Name'].isin(names)]
    filter_df_2 = filter_df_1[filter_df_1['Age'].isin(ages)]
    filter_df_3 = filter_df_2[filter_df_2['Salary'].isin(salarys)]  
    
    value_to_show = 0

    for colunas in columns_to_use:
        filter_df_3[colunas].sum()
        value_to_show = filter_df_3[options_dropdown]

    fig_pl_total = go.Figure()
    fig_pl_total.add_trace(go.Indicator(
        value=value_to_show
    ))

    return fig_pl_total    

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

```

I tried to solve this in a few ways, but usually, I encounter some of these errors

```auto
## Traceback *(most recent call last)*

* #### File "C:\Users\lauro.telles\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\indexes\base.py", line *3790*, in `get_loc`

return self._engine.get_loc(casted_key) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

* #### File "index.pyx", line *152*, in `pandas._libs.index.IndexEngine.get_loc`

* #### File "index.pyx", line *181*, in `pandas._libs.index.IndexEngine.get_loc`

* #### File "pandas\_libs\hashtable_class_helper.pxi", line *7080*, in `pandas._libs.hashtable.PyObjectHashTable.get_item`

* #### File "pandas\_libs\hashtable_class_helper.pxi", line *7088*, in `pandas._libs.hashtable.PyObjectHashTable.get_item`

* The above exception was the direct cause of the following exception:

> KeyError: '2'

```

or that:

`UnboundLocalError: cannot access local variable ‘value_to_show’ where it is not associated with a value`

---

<div class="post-metadata">

**Author:** ![adamschroeder](https://sea2.discourse-cdn.com/flex024/user_avatar/community.plotly.com/adamschroeder/32/17280_2.png) [@adamschroeder](https://community.plotly.com/u/adamschroeder)\
**Post date:** [December 18, 2023, 2:46pm UTC](https://community.plotly.com/t/how-to-connect-a-dropdown-menu-with-a-callback-to-select-a-column-for-sum-in-dash/80940/10 "2023-12-18T14:46:28Z")

</div>

Ok let’s see. So you’re trying to get the app user to choose a name, age and salary from the checklist. Then, you filter the data based on the name, age and salary selected.

And then, what is this part trying to do?

```auto
    for colunas in columns_to_use:
        filter_df_3[colunas].sum()
        value_to_show = filter_df_3[options_dropdown]

```

---

<div class="post-metadata">

**Author:** ![lauro.teles](https://avatars.discourse-cdn.com/v4/letter/l/eada6e/32.png) [@lauro.teles](https://community.plotly.com/u/lauro.teles)\
**Post date:** [December 18, 2023, 4:54pm UTC](https://community.plotly.com/t/how-to-connect-a-dropdown-menu-with-a-callback-to-select-a-column-for-sum-in-dash/80940/11 "2023-12-18T16:54:57Z")

</div>

This part is attempting to select one column based on the dropdown, sum up the numbers in that column, and display the result in the indicator.

---

<div class="post-metadata">

**Author:** ![adamschroeder](https://sea2.discourse-cdn.com/flex024/user_avatar/community.plotly.com/adamschroeder/32/17280_2.png) [@adamschroeder](https://community.plotly.com/u/adamschroeder)\
**Post date:** [December 18, 2023, 6:31pm UTC](https://community.plotly.com/t/how-to-connect-a-dropdown-menu-with-a-callback-to-select-a-column-for-sum-in-dash/80940/12 "2023-12-18T18:31:29Z")

</div>

but notice that you’re using `filter_df_3` for that. And that df is only created once name, age, and salary have been chosen.

---

<div class="post-metadata">

**Author:** ![AnnMarieW](https://avatars.discourse-cdn.com/v4/letter/a/ec9cab/32.png) [@AnnMarieW](https://community.plotly.com/u/AnnMarieW)\
**Post date:** [December 18, 2023, 10:08pm UTC](https://community.plotly.com/t/how-to-connect-a-dropdown-menu-with-a-callback-to-select-a-column-for-sum-in-dash/80940/13 "2023-12-18T22:08:09Z")

</div>

Hi @lauro.teles

When trying to debug a callback, it’s helpful to either use print statements or breakpoints to check the variables.

You are probably getting the key error because the dropdown component has the options defined like this:

```auto
{0: 'Nota1', 1: 'Nota2', 2: 'Nota3'}

```

When an item is selected, the dropdown `value` will be a 0, 1, or 2. These are not keys in the df.

---

<div class="post-metadata">

**Author:** ![hoatran](https://sea2.discourse-cdn.com/flex024/user_avatar/community.plotly.com/hoatran/32/21447_2.png) [@hoatran](https://community.plotly.com/u/hoatran)\
**Post date:** [December 19, 2023, 2:21am UTC](https://community.plotly.com/t/how-to-connect-a-dropdown-menu-with-a-callback-to-select-a-column-for-sum-in-dash/80940/15 "2023-12-19T02:21:40Z")

</div>

As @AnnMarieW suggestion, I think you should change options of your dropdown as `options = columns_to_use`  
With below code, I think it will work as your expectation:

```auto
import dash
from dash import dcc, html
from dash.dependencies import Input,Output
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
import dash_bootstrap_components as dbc
from dash_bootstrap_templates import load_figure_template
import numpy as np

data = {
    'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva'],
    'Age': [25, 30, 22, 35, 28],
    'Salary': [50000, 60000, 45000, 70000, 55000],
    'Nota1': np.random.randint(1, 10, 5),
    'Nota2': np.random.randint(1, 10, 5),
    'Nota3': np.random.randint(1, 10, 5)
}

df = pd.DataFrame(data)

df.loc['Total'] = df.sum(axis=0, numeric_only=True)
columns_to_use = ['Nota1','Nota2','Nota3']
marks = {i: option for i, option in enumerate(columns_to_use)}

app = dash.Dash()
app.layout =html.Div( children=[
    dbc.Row([
        dbc.Col([dbc.Card([
            dcc.Dropdown(
                        options=columns_to_use,
                        id='dropdown'),

            dcc.Checklist(df['Name'].value_counts().index,id='name'),
            dcc.Checklist(df['Age'].value_counts().index,id='age'),
            dcc.Checklist(df['Salary'].value_counts().index,id='salary')
    ]),dbc.Col([
        dcc.Graph(id='graph_1',)
    ])
        ])
            ])  
                ])

@app.callback(
    Output('graph_1','figure'),
    [Input('name','value'),
     Input('age','value'),
     Input('salary','value'),
     Input('dropdown','value')]
)
def update_fig(names,ages,salarys,options_dropdown):
    if not names or not ages or not salarys or not options_dropdown:
        return go.Figure()
    
    filter_df_1 = df[df['Name'].isin(names)]
    filter_df_2 = filter_df_1[filter_df_1['Age'].isin(ages)]
    filter_df_3 = filter_df_2[filter_df_2['Salary'].isin(salarys)]  
    
    filter_df_3.loc['Total'] = filter_df_3.sum(axis=0, numeric_only=True)
    value_to_show = filter_df_3[options_dropdown].iloc[-1]
    fig_pl_total = go.Figure()
    fig_pl_total.add_trace(go.Indicator(
        value=value_to_show
    ))

    return fig_pl_total    

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

```

 ![Screenshot 2023-12-19 092036](https://us1.discourse-cdn.com/flex024/uploads/plot/original/3X/4/2/428ab7b49f1464efba12d2cb888890510a3d6662.png)

---

<div class="post-metadata">

**Author:** ![lauro.teles](https://avatars.discourse-cdn.com/v4/letter/l/eada6e/32.png) [@lauro.teles](https://community.plotly.com/u/lauro.teles)\
**Post date:** [December 21, 2023, 2:01pm UTC](https://community.plotly.com/t/how-to-connect-a-dropdown-menu-with-a-callback-to-select-a-column-for-sum-in-dash/80940/16 "2023-12-21T14:01:53Z")

</div>

Thanks for all the help everyone, the way @ hoatran suggested worked.
