Python uses string as variable name

1. Use strings to refer to variable names.

For example, there are two variables a="bbb" and bbb={"c":1}. How to quote a to get {"c":1}, which is the value of the variable bbb represented by the value of a'bbb' .
I googled it and found the following four ways on http://www.douban.com/group/topic/2193745/ to convert a string into a variable, respectively:

>>> exec('bed=5')
>>> bed
5

>>> exec('bedict={}')
>>> bedict
{
    
    }

globals()['abc'] = 6

>>> globals()['bed'+str(3)] = {
    
    }
>>> bed3
{
    
    }

setattr(__builtins__, 'abc', 9)
__import__('sys')._getframe(0).f_globals['abc'] = 27

All four can be realized, so how to get {"c":1} by referencing a, it should be: >>> a='bbb'

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
>>> bbb={
    
    "c":1}
>>> exec('a=%s' % a)
>>> a
 
{
    
    "c": 1}

It can be achieved. Is there any other way?

In addition, if you want to dynamically change the a in the exec string'a=%s'% a, instead of specifying a, don't you need to get the name of the variable a first. That is the second question.

2. Get its string from the variable name

For example, the variable a='bbb', generally the result of quoting a is the value of a'bbb', then how do I get the name string'a' of a? Is it necessary?

Guess you like

Origin blog.csdn.net/qdPython/article/details/112846271