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" ))  
        dict.update({k:v})
    st.write(dict)

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.

2 Likes

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():
           input_field1
           input_field2
           submit button
           if submit button:
                  continue

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:
        st.session_state.data = []
    

    #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):
                placeholder2.empty()
                df = pd.DataFrame(st.session_state.data).transpose()
                #set the first row as new header
                df.columns = df.iloc[0]
                df = df[1:].reset_index(drop=True)
                st.write(df)
                break
            else:
                with placeholder1.form(key=str(num)):
                    input_feature = InputFeaturesValue(input=num)

                    if st.form_submit_button("add data"):
                        st.session_state.data.append(
                            {
                                'feature': input_feature.feature,
                                'value': input_feature.value 
                            }
                        )
                        st.session_state.num +=1
                        st.success("Successfuly recorded the data!")
                        placeholder1.empty()
                    else:
                        st.stop()

2 Likes

Great :v:

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