Home > database >  How do you convert a string into the name of an already created variable/list in python?
How do you convert a string into the name of an already created variable/list in python?

Time:05-03

So basically here's a simplified version of my problem:

list1 = ["hi", "hello", "bye"]
list2 = ["x", "y", "z"]
variable = either "list1" or "list2"

And so I want to print the list that the value of the variable currently is but since it's a string, if you print it, it'll just print "list1" or "list2". How could you print the correct list? Is there some function (I tried looking up one but I'm completely confused) that could convert it to a list name? Or some other way?

CodePudding user response:

Three choices come into my mind:

1- grab if from your current scope(at the module level, locals() and globals() are the same dictionary)

list1 = ["hi", "hello", "bye"]
print(locals()['list1'])

2- have a dictionary to map strings to the actual objects:

list1 = ["hi", "hello", "bye"]
d = {'list1': list1}
print(d['list1'])

3- use eval (defiantly not recommended when the input comes from somewhere else.)

list1 = ["hi", "hello", "bye"]
print(eval("list1"))

I would go with second solution if you ask.

CodePudding user response:

Try to avoid eval. I believe in your case simple switch is ok:

def return_list(name, list1, list2):
  if name == "list1":
    return list1
  if name == "list2":
    return list2
  return None

print(return_list("list1", list1, list2))

@jarmod's solution looks better, with small improvement:


listmap = {
 "list1": list1,
 "list2": list2
}

variable = "list2"
value = None
if variable in listmap.keys():
  value = listmap[variable]

print(value)

CodePudding user response:

The most common way to map from keys to values is to use a dictionary.

For example:

variable = "list1"

list1 = ["hi", "hello", "bye"]
list2 = ["x", "y", "z"]

mapping = { "list1": list1, "list2": list2 }
print(mapping[variable])
  • Related