I am dynamically rendering a set of radio buttons from a dictionary with Boolean values. When i change the selection from the rendered radio options then in the first instance it works as expected (updates the value in the dictionary and renders correct selected option) However, on the second time when i change the radio selection then it neither renders the correct radio option value nor it updates the value in the dictionary but on the third time it does. Now to correctly render the radio option I need to select the option two times (first time it won’t work but second time it will. I went through similar discussions on streamlit forum but couldn’t get it done. need some help with this. below is the code snipped for reproducibility:
st.session_state["temp_opt"] = {"One":True, "Two": False, "Three": True}
for key, value in st.session_state.get("temp_opt").items():
st.session_state["temp_opt"][key] = st.radio(label = f"r-{key}", options = [True, False], index = 0 if st.session_state["temp_opt"].get(key) else 1, key = f"rad-{key}")
Hi @m.sadiq.khan92,
One quick note about your post – can you please edit it so that your code is inside a code block? That makes it much easier to read and also for others to actually run. You can do that by adding three backticks (```) before and after your code.
My recommendation for fixing this code is to simply allow the streamlit automatic behavior of syncing a key’s value to session state. You can just do this:
import streamlit as st
st.radio("r-One", options=[True, False], index=0, key="One")
st.radio("r-Two", options=[True, False], index=1, key="Two")
st.radio("r-Three", options=[True, False], index=0, key="Three")
st.write(st.session_state)
And you’ll see that the values of the session state get updated automatically as you change the radio buttons:
You can see it in action here
If you need them all to be in a single dictionary, you can create a dictionary using on_change
like this.
2 Likes
Hi @blackary , I edited the post by putting backticks around the code and thanks for the suggestion. But this might not work in this scenario as the radio buttons along with their initial stats are defined inside a dictionary, and these has to be rendered via a loop. However, I found a work around it by rerunning the streamlit app by calling st.rerun()
method each time a radio button stat changes. Don’t know if it is a recommended solution but it does the job :).
Glad you found a working solution!