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

最佳答案

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

关于python - Python变量作为dict的键,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3972872/

10-10 11:40