Pass values from one widget to another in a form

I have a streamlit form with two multiselect widgets , but the options of the second multiselect widget should be based on the options selected in the first multiselect widget.

Example: ‘State’ is my first multi select widget and ‘City’ is my second multi select widget. Based on the State selection the cities belonging to that state should get populated in the second widget of the form
How can I solve this issue?

If I do not use forms the entire app reloads on selection od first widget


Hi @Nitya_Bhat

Please copy-paste this code into a file and test it before suitably modifying it for your use. Hopefully, this is what you are looking for.

import streamlit as st
import pandas as pd

data = [['Arizona', 'Phoenix'], ['Arizona', 'Tucson'], ['Arizona', 'Glendale'], 
        ['Montana', 'Billings'], ['Montana', 'Butte'],
        ['Wyoming', 'Cheyenne'],['Wyoming', 'Casper'], ['Wyoming', 'Gillette']]

df = pd.DataFrame(data, columns=['State', 'City'])

mystates = st.multiselect("States ?", df['State'].unique())
if len(mystates) > 0:
    mycities = df.get(['City']).where(df.get("State").isin(mystates)).dropna()
    mycities = st.multiselect("Cities ?", mycities)


Thanks for your Answer @Shawn_Pereira . I tried this solution but streamlit reloads on every select. How can i pass these in the Streamlit Form?

Hey @Nitya_Bhat!

That’s a great question. Unfortunately, quoting the docs:

A form cannot have interdependent widgets, i.e. the output of widget1 cannot be the input to widget2 inside a form.

Which means you can only achieve this behavior using @Shawn_Pereira’s elegant solution - btw thanks Shawn for showcasing pd.DataFrame.get - which will require an app rerun.



Thanks @arnaud

1 Like