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

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

问题描述

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

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天全站免登陆