I am probably not using dictionaries right but anyway, here is what I was trying to do:
- Set up a starting dictionary. This would be used as an empty template.
- pass the dictionary to a function. In the function it will be assigned a new variable name so I can do things to it.
- work on the dictionary by adding items to it.
- return the dictionary to some other variable in the main code.
- repeat the above for another variable in the main code. each time taking in that template dictionary and doing things to it.
But what seems to happen is that the "starting" dictionary is updated as well so when I pass it for the second time, its full of information I don't want.
Here is a minimum example:
startDeck = {
"deckSize":0,
"score":0,
"blackjack":False,
}
def playBlackjack(deck):
userDeck = dealCards(cards= deck,count=2)
compDeck = dealCards(cards= deck,count=1)
def dealCards(cards,count):
score = cards["score"]
deckSize = cards["deckSize"]
for n in range(count):
newCard = {}
deckSize+=1
score+=1
cardNo = "card" + str(deckSize)
newCard["card"] = "hearts"
newCard["value"] = 10
newCard["suit"] = "clubs"
cards[cardNo]=newCard
cards["score"]=score
cards["deckSize"]=deckSize
return cards
playBlackjack(startDeck)
I think that should work. I know it probably won't make much sense and maybe I should not be using dictionaries, but I did struggle with them and wanted to have a go with them to understand more.
But essentially what is happening here is all the dictionaries, whether its that "startDeck" one at the top (which I thought would be global and thus available to any function but I keep getting told by python that it can't see it?) or the dictionaries that I thought would only exist while the function runs, all end up filled with exactly the same information. And I don't understand why.