Is there a way to set unique key for widget inside a dictionary in session_state?

Using the key parameter in an input widget, a session state key is formed. Can this key be set within a dictionary initialized in session_state directly?

import streamlit as st

if 'vars' not in st.session_state:
    st.session_state.vars = {}

name=st.text_input("Name", key="name")

count_default = st.number_input('Count Default', key='count_def')

# need to set key inside dictionary in session_state
count_nested = st.number_input('Count Nested', key=vars['count_nes'])

st.write(st.session_state)
# SAMPLE OUTPUT NEEDED
# {
#     'name': 'Ramesh Kumar',
#     'count_def': 1,
#     'vars': {
#                 'count_nes': 2
#               }
# }

I’m aware of explicitly setting the value using:

st.session_state.vars['count_nes'] = count_nested

but I am working with many such fields and am looking to easily categorize them in dictionaries.

An alternative is to add a common prefix to these keys and have a function to look for them in st.session_state when needed.

For the sake of creating a var in the session, you may try this sample code.

import streamlit as st
from streamlit import session_state as ss

# Define the keys, default values, and widget functions for the widgets.
widgets = {
    'name': {'value': '', 'widget_func': st.text_input},
    'count_default': {'value': 0, 'widget_func': st.number_input},
    'count_nested': {'value': 0, 'widget_func': st.number_input}
}

# Initialize 'var' in session state if not present.
if 'var' not in ss:
    ss.var = {key: value['value'] for key, value in widgets.items()}

# Create widgets and update session state.
for key, info in widgets.items():
    widget_func = info['widget_func']
    label = key.replace('_', ' ').title()
    ss.var[key] = widget_func(label=label, key=key)

st.json(ss)

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