Session state with dictionary

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.

1 Like

@asehmi @deanhunter7 I have an additional question related to this :slight_smile: 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
1 Like

@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}
3 Likes

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