创建字典,其中键是变量名 [英] Create dictionary where keys are variable names

查看:41
本文介绍了创建字典,其中键是变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常想创建一个字典,其中键是变量名.例如,如果我有变量 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)}

这篇关于创建字典,其中键是变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆