How to get value from 'key' with loop

Hi everyone,

list_channels = ['I', 'II']
i = 0
for x in list_channels:
	i = i + 1
	widget = 'selectbox' + str(i)
	st.write('Channel', key=str(x))
	widget = st.selectbox('test', ['1','2'], key=str(x))

The ‘widget’ is generated with the ‘key’ in the loop, and I would like to retrieve values from those 'key’s for later use.
Is there any way to get values?

Assume: value of widget1 = ‘1’ and value of widget2 = ‘2’
Expectation: How to get value from widget1 and widget2?

Don’t really understand the intention of your code. widget1 and widget2 are strings, not variables to which you can assign st.selectbox component objects. The widget variable is overwritten in the loop.

Nevertheless, the values are available by key in st.session_state.

for x in list_channels:
1 Like

Hi Asehmi,

Thanks for your feedback.

You are right. That is my idea about how to get the value of those widgets, which are generated by the ‘key’.

Based on your comment, the ‘st.session_state’ will store the value of those widgets. Is that right?

Yes, print st.session_state and you’ll see all widgets’ state is automatically held, by their key in the session state dictionary. See API reference > State management.

1 Like