Search code examples
streamlit

Streamlit: customizing values in sidebar.selectbox()


Is there a way to show a name alias in the streamlit st.sidebar.selectbox()?

So for example:

raw_names = st.sidebar.selectbox(
    'Name:', get_name_list(), key='port'
)
    
def get_name_list() -> list:
    return ("Name A" ==  "A949", "Name B" ==  "B384")

And then, what is used for raw_names is only the second element of the list (so "A949" or "B384").

I have done this in a shiny app but not sure if possible with Streamlit as well.


Solution

  • Yes, you can use the format_func argument of selectbox.

    format_func

    Function to modify the display of the labels. It receives the option as an argument and its output will be cast to str.

    Source: the Streamlit documentation.

    You can use it like this:

    import streamlit as st
    
    d_convert = {
        "A949": "Name A",
        "B384": "Name B",
    }
    
    def convert_option(opt):
        return d_convert[opt]
    
    raw_name = st.sidebar.selectbox(
        'Name:', d_convert.keys(), key='port', format_func=convert_option
    )
    
    st.write(f"You chose {raw_name}")
    

    It gives:

    Name B is displayed in the selectbox and B384 on the displayed text