Python变量作为dict的键

atp*_*atp 61 python dictionary

有没有更简单的方法在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)
Run Code Online (Sandbox Code Playgroud)

dr *_*bob 67

for i in ('apple', 'banana', 'carrot'):
    fruitdict[i] = locals()[i]
Run Code Online (Sandbox Code Playgroud)

  • 一行``dict([(i,locals()[i])for i in('apple','banana','carrot')])` (14认同)
  • `{i: loc[i] for i in ('apple', 'banana', 'carrot')}`,无需创建列表并将其转换为字典。 (3认同)
  • 虽然这个问题大约是2.7,但请注意上述单行代码在Python 3中不起作用,因为`locals()`显然指向列表理解的范围。 (2认同)

Gre*_*ill 14

globals()函数返回包含所有全局变量的字典.

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

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

我意识到这可能不是你想要的,但它可以提供一些深入了解Python如何提供对变量的访问.

编辑:听起来你的问题可以通过首先简单地使用字典来解决:

fruitdict = {}
fruitdict['apple'] = 1
fruitdict['banana'] = 'f'
fruitdict['carrot'] = 3
Run Code Online (Sandbox Code Playgroud)


小智 6

单线是: -

fruitdict = dict(zip(('apple','banana','carrot'), (1,'f', '3'))
Run Code Online (Sandbox Code Playgroud)