Сaching the dictionary

Hello all,

I need to manually enter keys and values and fill the dictionary with them. But every time I enter a new key and value, the previous one is erased. How can I save all the entered values in the dictionary?

My simple code is:

with st.beta_container():
       d = {}
       col1, col2 = st.beta_columns(2)
       with col1:
              k = st.text_input('Key')
       with col2:
              v = st.text_input('Value')
       button = st.button('Add')
       if button:
              if k and v:
                     d[k] = v
       st.write(d)

Hi @Dmitriy, welcome to the Streamlit community!

Although it feels a bit boilerplate-y, you can accomplish what you want using the following:

import streamlit as st


@st.cache(allow_output_mutation=True)
def persistdata():
    return {}


with st.beta_container():
    d = persistdata()
    col1, col2 = st.beta_columns(2)
    with col1:
        k = st.text_input("Key")
    with col2:
        v = st.text_input("Value")
    button = st.button("Add")
    if button:
        if k and v:
            d[k] = v
    st.write(d)

Essentially, the st.cache decorator is telling Streamlit to persist this across runs, and allow_output_mutation=True allows you to modify the cached object. So the net result is the values persist over time.

Best,
Randy

1 Like

Hi Randy,

I’m new to python and found this useful framework for automating everyday tasks. Your advice helped, thank you very much! :slightly_smiling_face:

1 Like