创建字典,其中键是变量名

创建字典,其中键是变量名

问题描述:

我经常想创建一个字典,其中键是变量名.例如,如果我有变量 ab 我想生成: {"a":a, "b":b} (通常在函数结束时返回数据).

I quite regularly want to create a dictionary where keys are variable names. For example if I have variables a and b I want to generate: {"a":a, "b":b} (typically to return data at the end of a function).

python 中是否有任何(理想情况下内置的)方法可以自动执行此操作?即有一个函数使得 create_dictionary(a,b) 返回 {"a":a, "b":b}

Are there any (ideally built in) ways in python to do this automatically? i.e to have a function such that create_dictionary(a,b) returns {"a":a, "b":b}

您是否考虑过创建类?类可以被视为字典的包装器.

Have you considered creating a class? A class can be viewed as a wrapper for a dictionary.

# Generate some variables in the workspace
a = 9; b = ["hello", "world"]; c = (True, False)

# Define a new class and instantiate
class NewClass(object): pass
mydict = NewClass()

# Set attributes of the new class
mydict.a = a
mydict.b = b
mydict.c = c

# Print the dict form of the class
mydict.__dict__
{'a': 9, 'b': ['hello', 'world'], 'c': (True, False)}

或者,如果您想传递变量名称列表,可以使用 setattr 函数:

Or you could use the setattr function if you wanted to pass a list of variable names:

mydict = NewClass()
vars = ['a', 'b', 'c']
for v in vars: 
    setattr(mydict, v, eval(v)) 

mydict.__dict__
{'a': 9, 'b': ['hello', 'world'], 'c': (True, False)}