Python变量作为字典键

112 投票
12 回答
305668 浏览
提问于 2025-04-16 05:45

在Python(2.7)中有没有更简单的方法来做到这一点?注意:这并不是一些复杂的操作,比如把所有本地变量放进一个字典里。只是我在一个列表中指定的那些变量。

apple = 1
banana = 'f'
carrot = 3
fruitdict = {}

# I want to set the key equal to variable name, and value equal to variable value
# is there a more Pythonic way to get {'apple': 1, 'banana': 'f', 'carrot': 3}?

for x in [apple, banana, carrot]:
    fruitdict[x] = x # (Won't work)

12 个回答

11

一句话代码就是这样写的:

fruitdict = dict(zip(('apple','banana','carrot'), (1,'f', '3'))
24

globals() 这个函数会返回一个字典,里面包含了你所有的全局变量。

>>> apple = 1
>>> banana = 'f'
>>> carrot = 3
>>> globals()
{'carrot': 3, 'apple': 1, '__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, 'banana': 'f'}

还有一个类似的函数叫 locals()

我知道这可能不是你想要的答案,但它可以帮助你理解 Python 是怎么让你访问变量的。

编辑:听起来你的问题可能更适合直接使用字典来解决:

fruitdict = {}
fruitdict['apple'] = 1
fruitdict['banana'] = 'f'
fruitdict['carrot'] = 3
107

这段代码是用来做一些特定操作的。它可能涉及到一些编程语言的基本语法和功能。具体来说,它可能会包含变量的定义、函数的调用以及一些控制流程的语句,比如循环和条件判断。

如果你是编程新手,可以把这段代码想象成一个食谱。食谱里会告诉你需要哪些材料(变量),然后一步一步教你怎么做(函数和控制流程)。通过这些步骤,你可以得到你想要的结果。

记住,编程就像做饭,开始的时候可能会觉得复杂,但只要多练习,就会越来越熟练。

for i in ('apple', 'banana', 'carrot'):
    fruitdict[i] = locals()[i]

撰写回答