0

I have a set of dictionaries that are labeled without quotations as such:

a = {records: "A", ...}
b = {records: "A", ...}

And I have a list inside a string that contains the set of dictionary names like this:

list_of_dicts = "[a, b]"

I am trying to convert this to a list with the dictionary names without quotations so that I can make function calls with the dictionary names. I would like the list to end up like this:

list_of_dicts = [a, b]

The problem is that every attempt I to convert this list inside a string has failed. I have tried to strip the quotations like so:

dict_names = list_of_dicts.strip('][').split(', ')

But this has resulted in the variables inside the list to be converted to string:

dict_names = ['a', 'b']

I also have tried to use eval to convert the variables to dictionaries, but none of this has worked. Is my approach incorrect? Or is it possible to convert this string into a list with the dictionary names? Any suggestions would be appreciated. Thank you in advance.
EDIT:
So I found this SO post: Get name of dictionary Where another person attempted to place the dictionary names into a list in order to iterate through it. The top comment following the post states: "Dictionaries do not inherently have names. Variables, as a general rule, do not inherently have names. If you're trying to get the name of the variable you assigned it to, I don't think that can be done, since you could have multiple variables pointing to the same dictionary". Is this true? Does that mean that there is no way of converting these string values to dictionary names within a list?

  • "*labeled without quotations*" does not mean anything, what is the real object `a`? – mozway Mar 07 '22 at 19:19
  • How did you use `eval`? What happened? – C.Nivs Mar 07 '22 at 19:21
  • It might be helpful to have a little more context about what you're trying to accomplish overall. While there are ways to get a variable value given it's string name, there are very few cases where that's what you *want* to do. – Nick Bailey Mar 07 '22 at 19:24
  • @mozway The object a is a dictionary. The object a is found inside a list which is a string. I would like to convert the string to a list of just the dictionary names. Does that help? – learningtoprogram123 Mar 07 '22 at 19:42

1 Answers1

0

You could make use of globals():

>>> a = 'A'
>>> b = 'B'
>>> list_of_dicts = "[a, b]"
>>> [globals().get(item.strip(), None) for item in list_of_dicts[1:-1].split(',')]
['A', 'B']
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47