1

I'm new to coding so please forgive me if this question have already been answered elsewhere, but I tried looking for awhile and couldn't find an answer.

To clarify the issue I am trying to solve, I'll illustrate it with the code below:

#Sample problem
ABCD = []
KEY = "ABCD"
data = 123
[str(KEY)].append(data)

print(f"{ABCD}")

Here I am attempting to call the append method for the list ABCD but with the variable KEY which contains the string "ABCD" This code doesn't work but illustrates my question. I am wondering if it is possible to call the method such as the one I have above using a variable instead of hard coding it like:

if KEY == "ABCD":
    ABCD.append(data)

print(f"{ABCD}")

Thank you!!

Gee
  • 11
  • 1
  • 3
    you can keep list in dictionary and then you can use string to access it. `d = { "ABCD": [] }` `d[KEY].append(data)` – furas May 19 '21 at 02:26
  • 1
    there is `globals()[KEY]` and `locals()[KEY]` to access variables using string but usually it is resolved using normal dictionary to keep elements. – furas May 19 '21 at 02:30
  • Thanks!! I just updated my code with your solution and now it looks much cleaner!! I was annoyed at how ugly my code was since I pretty much had to hard code a bunch of if statements. – Gee May 19 '21 at 03:15
  • [Keep data out of your variable names](https://nedbatchelder.com/blog/201112/keep_data_out_of_your_variable_names.html) – wim May 19 '21 at 03:18

2 Answers2

0

I think I shall share my method not using eval. It accesses all the local variables currently in the script. The program uses this to it's advantage allowing it to locate whether a variable exists or not. Another thing used in this program are dictionaries which help us store our information neatly. Though it might be a tad bit overcomplicated Testcase 1 #ABCD does exist

ABCD = []
KEY = "ABDC"
data = 123
import sys, pprint
sys.displayhook = pprint.pprint
variables = locals()
#check if KEY can be found in locals
if variables.get(KEY) != None:
    #create a dict ,KEY = key, "[]" is value
    #{'ABCD': []}
    varDict = {KEY:variables.get(KEY)}
    #append data
    varDict[KEY].append(data)
    print(varDict)
#KEY is not variable in locals
else:
    print('could not find')

expected output

{'ABCD': [123]}

Testcase 2 #ABCD is not existant, instead ABDC.

ABCD = []
KEY = "ABDC"
data = 123
import sys, pprint
sys.displayhook = pprint.pprint
variables = locals()
#check if KEY can be found in locals
if variables.get(KEY) != None:
    #create a dict ,KEY = key, "[]" is value
    #{'ABCD': []}
    varDict = {KEY:variables.get(KEY)}
    #append data
    varDict[KEY].append(data)
    print(varDict)
#KEY is not variable in locals
else:
    print('could not find')

expected output

could not find

Let me know if a test case does not work.

Buddy Bob
  • 5,829
  • 1
  • 13
  • 44
-1

You can pass eval an f string to do that, but furas' method is much safer/better.

ABCD = []
KEY = "ABCD"
data = 123
eval(f'{KEY}.append(data)')
print(ABCD)

More on the dangers of eval here

In addition, there are a number of methods for storing and referencing objects without having to put them into a key-value pair relationship (in dict) but furas' method is the most direct and useful for most cases.