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