Create inputs widget dynamically and collect their values

Hello all,

I want to edit a dataframe of size n x m with n and m changing each time I am using the app. I am trying to find a work around the fact that a user cannot edit a st.dataframe by using input widgets such as st.text_input. Which means that for each column I will create n-text_inputs in a for loop as shown below:

Code snippet:

    for i, row in enumerate(df['transfer_date']):
        st.text_input(label='You can write a date', value=row, max_chars=50,
                      label_visibility='hidden', key=f'date{i}')

My issue is that since I am doing that in a for loop, I can’t really define a variable name for each text_input. Without having defined this variable name I can’t find a way of collecting the values from each text_input.

Can I access the values of each st.text_input, when creating them this way ? Or should I find another way of defining my st.text_input ?

I appreciate the help,
Cheers,
Baptiste

The values are stored in st.session_state with the keys associated with the widgets.

for i in range(len(df['transfer_date'])):
    st.write(st.session_state[f'date{i}'])
1 Like

Awesome, thanks a lot !

You could also use an empty dictionary instead:

my_dict = {}
for i, row in enumerate(df['transfer_date']):
    my_dict[i] =  st.text_input(label='You can write a date', value=row, max_chars=5, 
                        label_visibility='hidden', key=f'date{i}')

This will create a text input for each row and save its value in a dictionary.

1 Like