0

I have a simple problem in python. I am trying to create a varible which uses the value of another variable in its name. A pertinent part of the code is:

for m in range (1,4):
    if m ==1:
        suffix = "top"
    elif m == 2:
        suffix = "mid"
    elif m == 3:
        suffix = "btm"
                
    game_battles_{suffix} = [["Match", "Winner", suffix]]
    print(game_battles_suffix)

The issue is I won't three versions of game_battles_{suffix} - game_battles_top , mid, btm etc

I have a feeling this is an easy one but I can quite figure it out

martineau
  • 119,623
  • 25
  • 170
  • 301
MWallace
  • 59
  • 6
  • Don't do it that way at all. Have just one variable `game_battles` that's a dict, with `top`, `mid` and `btm` as keys. That way you can set `game_battles[suffix] = ...` – Charles Duffy Oct 22 '21 at 16:01
  • Still kinda cinfused. The issue is this suffix is to be used across a large function. Initially I had 3 identical functions, the only difference being each looked at a dataset called either top, mid or btm (lists of games which had been assigned a score of 1, 2 or 3). – MWallace Oct 22 '21 at 16:26
  • What part of the dict approach _can't_ you use across a large function? – Charles Duffy Oct 22 '21 at 16:27
  • It worked fine but I thought I could use a loop to generate all the outputs of the three functions without having to repeat the function with a tiny difference in text – MWallace Oct 22 '21 at 16:27
  • Yes, and you totally can. `for suffix in "top", "mid", "btm": ...` will work fine when you refer to `game_battles[suffix]` inside the loop. – Charles Duffy Oct 22 '21 at 16:28
  • Never mind. I will try to figure things out by trial and error. I am too new at python obviously. I'll figure something out – MWallace Oct 22 '21 at 16:28
  • thanks, I'll give it a shot and see how I go – MWallace Oct 22 '21 at 16:29
  • (since you're a beginner -- when I said you need to make a variable "that's a dict", that means you'd start with `game_battles = {}` initializing the variable before the loop) – Charles Duffy Oct 22 '21 at 16:36

0 Answers0