gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:08:11 24 4
gpt4 key购买 nike

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

python 中是否有任何(最好是内置的)方法来自动执行此操作?即有一个函数 create_dictionary(a,b) 返回 {"a":a, "b":b}

最佳答案

您是否考虑过创建一个类(class)?类可以看作是字典的包装器。

# 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 函数:

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)}

关于python - 创建字典,其中键是变量名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39818733/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com