**DuplicateWidgetID** : There are multiple identical `st.selectbox` widgets with the same generated key

Hi, i am getting below errors when running the app. i tried to pass a key into however not working. how do i fix this?

DuplicateWidgetID : There are multiple identical st.selectbox widgets with the same generated key.

When a widget is created, it’s assigned an internal key based on its structure. Multiple widgets with an identical structure will result in the same internal key, which causes this error.

To fix this error, please pass a unique key argument to st.selectbox .

codes as below:
cat_var, num_var = st.beta_columns(2)
for col in df.columns:
if df[col].dtype == ‘object’:
cat_var.selectbox(‘select feature:’,df.select_dtypes(include=‘object’)
fig, ax = plt.subplots()
sns.countplot(df[col],ax=ax)
plt.xticks(rotation=45)
cat_var.pyplot(fig)
else:
num_var.selectbox(‘numeric feature’,df.select_dtypes(exclude=‘object’).columns)
fig, ax = plt.subplots()
ax.hist(df[col])
plt.xticks(rotation=45)
num_var.pyplot(fig)

Give this a go; it should add a unique key to each selectbox widget:

import random

keys = random.sample(range(1000, 9999), len(df.columns))

cat_var, num_var = st.beta_columns(2)
for i, col in enumerate(df.columns):
    if df[col].dtype == ‘object’:
        cat_var.selectbox(
            ‘select feature:’,
            df.select_dtypes(include=‘object’),
            key = keys[i])
        fig, ax = plt.subplots()
        sns.countplot(df[col],ax=ax)
        plt.xticks(rotation=45)
        cat_var.pyplot(fig)
    else:
        num_var.selectbox(
            ‘numeric feature’,
            df.select_dtypes(exclude=‘object’).columns,
            key = keys[i])
        fig, ax = plt.subplots()
        ax.hist(df[col])
        plt.xticks(rotation=45)
        num_var.pyplot(fig)

HTH

2 Likes