相关疑难解决方法(0)

Python变量作为dict的键

有没有更简单的方法在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)

python dictionary

61
推荐指数
3
解决办法
14万
查看次数

标签 统计

dictionary ×1

python ×1