Help request about st.selectbox

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?

This is possible.

Store your option values in a list.

OPTIONS = ['apple', 'book']

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}')

Sample output

Thx for your help. Your example works good, but a think to a mysql relational database, where i could have for example, with semplification:

table: tbstocks
fields:

idstock , integer AI
stock, varchar(50)

when i read recordset i have idstock values that could not be sequential:

idstock stock
522 1st Source Corporation
384 3M Company
66 A. O. Smith Corporation
34 Abbott Laboratories
31 AbbVie Inc.
32 ABM Industries Incorporated
36 Accenture plc
37 Adobe Inc.
57 Advanced Micro Devices, Inc.
45 Aflac Incorporated
28 Agilent Technologies, Inc.
68 Air Products and Chemicals, Inc.
33 Airbnb, Inc.
49 Akamai Technologies, Inc.
52 Alaska Air Group, Inc.
50 Albemarle Corporation
71 Alexandria Real Estate Equities, Inc.
24 Algebris Ig Financial Credit R Cap Eur

now i want to create a db editor with streamlit with a combobox containing stock variable

when the event is clicked , the selected stock should give also theitstock value

to edit a specific record i must have an id to edit

i dont know if this component is able to do that

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]}')

Sample output

thx i will try your code and i will report it to the forum.

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