Selectbox returns wrong id when duplicate labels

Please take a moment to search the forum and documentation before posting a new topic.
If you’re creating a debugging post, please include the following info:

  1. Are you running your app locally or is it deployed? locally
  2. Share the Streamlit and Python versions. 1.46.1 and 3.13.1

I am trying to create a selectbox from a list of dictionaries that includes and name and an id. I want the user to see the (possibly duplicated_ names but to have the unique id returned. I find that this does not work. When I pick each duplicated name I get the same id (the last one in the list). Here is a failing example.

import streamlit as st
data = [{"name":'Ron', "id": 1}, {"name":'Fred', "id": 2}, {"name":'George', "id": 3}, {"name":'Fred', "id": 4}, {"name":'George', "id": 5}]

labels = [x["name"] for x in data]
options = [x["id"] for x in data]
dic = dict(zip(options, labels))

a = st.selectbox('Choose name', options=options, format_func=lambda x: dic[x])

st.write(a)
2 Likes

That definitely does seem to be a bug. I don’t see anything about that when looking at open issues, so feel free to create a new one Sign in to GitHub · GitHub if you’d like

As a silly work-around, you can add some invisible characters to the names if you want them to stay unique, and this seems to fix the issue

import streamlit as st

data = [
    {"name": "Ron", "id": 1},
    {"name": "Fred", "id": 2},
    {"name": "George", "id": 3},
    {"name": "Fred", "id": 4},
    {"name": "George", "id": 5},
]

labels = [x["name"] for x in data]
options = [x["id"] for x in data]
dic = dict(zip(options, labels))

new_d = {}
for k, v in dic.items():
    new_d[k] = str(v) + "\u200b" * k

st.write(new_d)

a = st.selectbox("Choose name", options=new_d.keys(), format_func=lambda x: new_d[x])

st.write(a)

@kalantar

It’s a regression that happened when we introduced accept_new_options for st.multiselect and st.selectbox. As I understand it, it’s the same underlying problem for both widgets. Previously, items were tracked (internally) by their position, but now (because of the ability to add options), items are tracked by their label. This means, it’s always the first instance of a label that comes back as selected.

Have the same issue, broke my app. Is it considered to be a bug and will be fixed or have to find another way around?

Please upvote the bug report to help us track the severity select box does not support multiple not unique labels anymore. v.1.46.1 · Issue #11949 · streamlit/streamlit · GitHub

1 Like

Yes, I am facing the same issue in my app currently. Please fix this as soon as possible, since it’s a pretty common use-case to have duplicate labels in a selectbox.

Upvoted the issue on Github.