I am doing a project in streamlit, where I am making a drop-down list of every state, then based on the selected state, the city drop-down box will only show cities from that state. My problem is that my values for states goes like {'full name of state': 'state abbreviation'}. The cities' data only has city and state abbreviation, so when I check to see if the option is selected, I can only show the abbreviations.
import streamlit as st
import geonamescache
states_dict = dict()
cs = ["Select a city"]
col1, col2, col3 = st.columns(3)
with col2:
gc = geonamescache.GeonamesCache()
city = gc.get_cities()
states = gc.get_us_states()
if "disabled" not in st.session_state:
st.session_state.disabled = True
def callback():
st.session_state.disabled = False
# ---STATES---
for state, code in states.items():
states_dict[code['name']] = state
option_s = st.selectbox("Select a State", states_dict.items())
if option_s == "Select a State":
st.write("#")
else:
st.write("You selected:", option_s)
# ---CITIES---
for city in city.values():
if city['countrycode'] == 'US':
if city['admin1code'] == option_s[1]:
cs.append(city['name'])
option_c = st.selectbox("Select a city", cs, disabled=st.session_state.disabled, on_change=callback())
if option_c == "Select a city":
st.write("#")
else:
st.write("You selected:", option_c)
Right now I have it showing both values from the Dictionary, but I'm trying to get it for example to just be California in the state and show every city from california matching CA from states_dict to city['admin1code'].
Does this work as you want:
What changed is that only
keys()are displayed in thestatesdictionary, so that abbreviations are not displayed. Then thestates_dictis called again to check the abbreviation equality with the option selected.Otherwise I just extracted the
callbackand thedisabledoption from thewithstatement, but this should have no effect.