简体   繁体   中英

Convert List in String to a List of Dictionary Names

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?

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM