Unique key for every items in radio button

Hi,

Have do you assign a key for each item in a radio box?

choices = st.sidebar.radio('Filter', ('United States', 'Canada'))
selected = 'US' if choices == 'United States' else 'CA'

I hope not to use a dictionary or function or the like to return the code assigned to the radio item.

TIA!

Hi @jeisma -

From the given example, there are only two options in the radio, so it feels like you can specify this directly in the code without much effort. Is your example more complex?

Best,
Randy

Hi,

Im not sure if I get what you mean with specify in the code. Did you mean I can actually assign a key for each item in the list?

The list can be 2, 10, 30โ€ฆ items long.

Thanks.

The point was that your example only showed ('United States', 'Canada'), so that writing out the two combinations wouldnโ€™t be that much work to do.

If the list can be really long, then you can use the format_func argument:

import streamlit as st

mapping = {"US": "United States", "CA": "Canada"}

choices = st.sidebar.radio("Filter", ("US", "CA"), format_func=lambda x: mapping[x])

choices # will show "United States" in radio button widget, return "US" to variable 'choices'

I hope not to use a dictionary or function or the like to return the code assigned to the radio item.

Not sure there is a different solution than the one I provide above.

Best,
Randy

2 Likes

Hi Randy,

This works. Thank you!

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.