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"):
scoredf = pd.DataFrame(scoredict,index=[0])

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 :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 = 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}