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:
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)?
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()