Multiselect - display elements in list order

Hi, I am learning python and developing a data app in Streamlit.

I want to use the st.multiselect function with years (categorical data), respecting the order of my list years_series.

My current code allows users to see a pre-selected list of years. This works fine. But any further selections (by the user) are displayed after the pre-selection - which is not consistent.

I would like to have all the selected items be displayed in the order of my list (dates are ascending from 1998 to 2021). I don’t know if it is possible and how to do it?

Any suggestion would be useful.Thanks.

image

Code snippet:

> df = pd.read_csv('../data/dash/streamlit_v2.csv')
> year_series = df.drop_duplicates(subset=['Year'])['Year']
> year_tail = year_series.tail(11)
> year_selected = st.sidebar.multiselect('Choose years', year_series, year_tail)

You can use session state to manipulate the behavior of widgets. For example:

import streamlit as st

if 'years' not in st.session_state:
    st.session_state.years = list(range(2010,2021))

selection = st.session_state.years

def sort_years():
    st.session_state.years.sort()

st.multiselect('Years',range(1990,2021), selection, key='years', on_change=sort_years)
2 Likes

@mathcatsand, thank you very much! I had to change the data type from series to list (in my code) to make it work.

1 Like

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