Python变量作为dict的键 [英] Python variables as keys to dict

查看:170
本文介绍了Python变量作为dict的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python(2.7)中有一个更简单的方法来做到这一点吗?注意:这不是什么好奇的,就像将所有的局部变量放在字典中一样。只是我在列表中指定的那些。

  apple = 1 
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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆