I am running a test application locally
Streamlit version 1.29.0
Python version 3.11.7
i have the followiong data list:
id:1
value: apple
id:2
value:book
Request: with st.selectbox i will see apple and book, is it possible to memorize also the id, so when i click and select ‘book’ the reference value selected is 2?
The index of apple is 0 and that of book is 1. That is how python assign indexes to a list. Since you want apple to be 1 and book to be 2, we will just add 1.
The way to get the index of a given list is this.
selected_index = OPTIONS.index(selected)
Full sample code.
import streamlit as st
OPTIONS = ['apple', 'book']
selected = st.selectbox(label='Please select', options=OPTIONS)
selected_index = OPTIONS.index(selected)
# The list index starts at 0, so we add 1.
selected_index += 1
st.write(f'Selected: {selected}')
st.write(f'Index: {selected_index}')
If your data is a list of tuple, convert it to dict of stock as key and idstock as value, and use the dict keys as option in selectbox. The idstock can be taken from the dict as value
import streamlit as st
data = [
(522, "1st Source Corporation"),
(384, "3M Company")
]
# Convert list of tuple to a dict.
dic = {v: i for i, v in data}
selected = st.selectbox('Please Select', options=list(dic.keys()))
st.write(f'selected: {selected}, index: {dic[selected]}')