Python变量作为dict的键 [英] Python variables as keys to dict
本文介绍了Python变量作为dict的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
apple = 1
$我在('苹果','香蕉','胡萝卜')中的p $ p>
banana ='f'
carrot = 3
fruitdict = {}
#我想设置键等于变量名,值等于变量值
#有更多的Pythonic方式来获取{ '苹果':1,'香蕉':'f','胡萝卜':3}?
for [apple,banana,carrot]:
fruitdict [x] = x#(不行)
解决方案
:
fruitdict [i] =本地人()[i]
Is there an easier way to do this in Python (2.7)?: Note: This isn't anything fancy, like putting all local variables into a dictionary. Just the ones I specify in a list.
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变量作为dict的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文