i tried this code and i cant make this dictionary to work
import streamlit as st
import pandas as pd
import random
if "scoredict" not in st.session_state:
st.session_state.scoredict["Player"] = 0
st.session_state.scoredict["Computer"] = 0
def AddPlayer():
scoredict["Player"] += 1
def AddComputer():
scoredict["Computer"] += 1
if st.button("Rock"):
Computerguess = random.choice(('Scissors','Paper'))
st.write('Computer used {}'.format(Computerguess))
if (Computerguess == "Scissors"):
AddPlayer()
else:
AddComputer()
scoredf = pd.DataFrame(scoredict,index=[0])
st.write(scoredf)
Wherever you have scoredict alone, you need to use st.session_state.scoredict. I’d also initialize st.session_state.scoredict = {} to ensure Python knows scoredict is a dict.
@asehmi@deanhunter7 I have an additional question related to this Isn’t session_state a already a dictionary in itself? I ask because I believe you can also do:
if "player" not in st.session_state:
st.session_state.player= 0
st.session_state.computer = 0
@marduk - No, st.session_state is a proxy for something that acts like a dict with the extra ability to directly assign and initialize new attributes. You can’t do attribute assignment in standard Python dicts; you must use the square brackets notation. Hence why scoredict must to be assigned to {} first, and then initialized with values using the square brackets syntax. You could more compactly do:
if "scoredict" not in st.session_state:
st.session_state.scoredict = {"Player": 0, "Computer": 0}
Thanks for stopping by! We use cookies to help us understand how you interact with our website.
By clicking “Accept all”, you consent to our use of cookies. For more information, please see our privacy policy.
Cookie settings
Strictly necessary cookies
These cookies are necessary for the website to function and cannot be switched off. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms.
Performance cookies
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us understand how visitors move around the site and which pages are most frequently visited.
Functional cookies
These cookies are used to record your choices and settings, maintain your preferences over time and recognize you when you return to our website. These cookies help us to personalize our content for you and remember your preferences.
Targeting cookies
These cookies may be deployed to our site by our advertising partners to build a profile of your interest and provide you with content that is relevant to you, including showing you relevant ads on other websites.