'Reference a variable from a string in Python [duplicate]

I have a number of global variables in my script (e.g. group_1, group_2, group_3) and I am trying to refer to them inside a function.

def plot(group_number):
   return(f"group_{group_number}")

I would like the function in this case to return the global variable group_2 when I run plot(2). Is there a way to turn this string "group_2" into the variable group_2?



Solution 1:[1]

Global variables are available through the dict returned by globals(). So,

>>> group_1 = "one"
>>> group_2 = "two"
>>> group_3 = "three"
>>> 
>>> def plot(group_number):
...     return globals()[f"group_{group_number}"]
... 
>>> plot(2)
'two'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tdelaney