小编典典

Python变量作为dict的键

python

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

阅读 248

收藏
2020-12-20

共1个答案

小编典典

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