Iterate dictionary in streamlit

Hi all. I want to make dictionary with iteration in streamlit closed to something like this:-`

    dict = {}
    num = input("How many elements?")
    for i in range(int(num)):
        k = str(input("Insert your key "))  
        v = float(input("Insert your value" ))  

I try to change it to widget st.text_input for the “key” and “value” but it shows error like this:

Is there any other idea I can do this in streamlit?

Thank you

Try adding str(i) as a key to the text input fields or some random strings that change on each iteration.


Hi, I tried it and it worked. Thank you. Just, the widget will replicate to the number of my “num” variable input. Is there any other way that I can just have one input widget (for k and v respectively)?

Try using this kind of syntax:

placeholder = st.empty()
for loop:
    with placeholder.container():
           submit button
           if submit button:

Refer to this st.empty - Streamlit Docs

Not entirely sure if this will work. Add conditions like after submit button the loop should progress to the next iteration.

Yes. you are correct. I found another method by using class and session_state…

 if 'num' not in st.session_state:
        st.session_state.num = 1
    if 'data' not in st.session_state: = []

    #state class for input features and data
    class InputFeaturesValue:
        def __init__(self, input):
            st.title(f"Data Input {input}")
            self.feature = st.text_input("features")
            self.value = st.text_input("value")

    def data():
        placeholder1 = st.empty()
        placeholder2 = st.empty()

        while True:

            num = st.session_state.num

            if placeholder2.button("finish", key=num):
                df = pd.DataFrame(
                #set the first row as new header
                df.columns = df.iloc[0]
                df = df[1:].reset_index(drop=True)
                with placeholder1.form(key=str(num)):
                    input_feature = InputFeaturesValue(input=num)

                    if st.form_submit_button("add data"):
                                'feature': input_feature.feature,
                                'value': input_feature.value 
                        st.session_state.num +=1
                        st.success("Successfuly recorded the data!")

1 Like

Great :v:

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