Dynamically created Multiple Checkbox

I have a dataset having different country name and as the count of unique countries are large I can’t put it manually in the checkbox. Also I want to add “All” & “None” option in the checkbox. I want to do the whole process dynamically. For better understanding I attach


an example. I will be grateful if anyone give me a solution or if the solution is already given kindly attach the link.

Hi @udo,
Welcome to the community,
I implemented a very hacky way of achieving what you want, but it works
animation

import streamlit as st

if 'dummy_data' not in st.session_state.keys():
    dummy_data = ['IND','USA','BRA','MEX','ARG']
    st.session_state['dummy_data'] = dummy_data
else:
    dummy_data = st.session_state['dummy_data']

def checkbox_container(data):
    st.header('Select A country')
    new_data = st.text_input('Enter country Code to add')
    cols = st.columns(10)
    if cols[0].button('Add Coutry'):
        dummy_data.append(new_data)
    if cols[1].button('Select All'):
        for i in data:
            st.session_state['dynamic_checkbox_' + i] = True
        st.experimental_rerun()
    if cols[2].button('UnSelect All'):
        for i in data:
            st.session_state['dynamic_checkbox_' + i] = False
        st.experimental_rerun()
    for i in data:
        st.checkbox(i, key='dynamic_checkbox_' + i)

def get_selected_checkboxes():
    return [i.replace('dynamic_checkbox_','') for i in st.session_state.keys() if i.startswith('dynamic_checkbox_') and st.session_state[i]]


checkbox_container(dummy_data)
st.write('You selected:')
st.write(get_selected_checkboxes())

let me know if it helped
Thanks,
Akshansh

2 Likes

Sorry to inform you that it is not working. Can you modify or simplify this code.

Hi @akshanshkmr thanks it worked for me but I want to use this code in multiple time my project so I defined it as a function. But it showed me an error as I don’t give unique key. So can you help me to solve this problem? I attached the error.

Hi @udo,

Glad it worked for you, it’s just a matter of providing a unique key to each checkbox that you create, maybe you can add a “key” parameter to your function and prefix that key to the checkbox keys.

Thanks,
Akshansh