-2

Sorry if the title is confusing but I couldn't think of a better way to word it. I'm making a game with a friendship system and this is essentially what I'm trying to do:

playerChar = "Adam";
opinion_[playerChar]_Betty = 20;

so that later I can check

if opinion_Adam_Betty == 20;

playerChar could be set to Adam, Betty, or Carmen.

So if playerChar was set to Adam, then opinion_[playerChar]_Betty and opinion_Adam_Betty would actually refer to the same variable, but if playerChar was set to Carmen, opinion_[playerChar]_Betty would be referring to the variable opinion_Carmen_Betty instead, and no longer be the same variable as opinion_Adam_Betty.

In essence, I want opinion_[playerChar]_Betty to be able to refer to different variables depending on what the variable playerChar is set to. Not sure if this is possible or not (or if I'm just overcomplicating things) but it would make some things super convenient for me if it were.

1 Answers1

2

Sounds like you want to use nested dictionaries. Using defaultdict specifically saves you a bunch of init work:

from collections import defaultdict

opinion = defaultdict(lambda: defaultdict(int))

playerChar = "Adam"
opinion[playerChar]["Betty"] = 20

if opinion["Adam"]["Betty"] == 20:
    print("Adam likes Betty <3")

if opinion["Betty"]["Adam"] < 20:
    print("it's not mutual tho </3")
Samwise
  • 68,105
  • 3
  • 30
  • 44
  • Thank you so much, that's exactly what I needed!! I'm still really new to Python and I had no idea dictionaries could be used in that way – Questionnaire Oct 20 '21 at 16:08