【发布时间】:2018-05-06 06:03:39
【问题描述】:
我正在寻找一种更优雅、更通用的方法来用变量填充字典:
dic = {}
fruit = 'apple'
vegetable = 'potato'
dic['fruit'] = fruit
dic['vegetable'] = vegetable
有没有更通用的方法而不使用引号中的变量名?
【问题讨论】:
标签: python
我正在寻找一种更优雅、更通用的方法来用变量填充字典:
dic = {}
fruit = 'apple'
vegetable = 'potato'
dic['fruit'] = fruit
dic['vegetable'] = vegetable
有没有更通用的方法而不使用引号中的变量名?
【问题讨论】:
标签: python
如果引号是问题所在,那该怎么办?
fruit = 'apple'
vegetable = 'potato'
dic = dict(
fruit = fruit,
vegetable = vegetable
)
【讨论】:
可能不是一个非常优雅的解决方案,但您可以使用 locals() 检索变量,然后将它们转换为字典。
fruit = 'apple'
vegetable = 'potato'
dic = {key:value for key, value in locals().items() if not key.startswith('__')}
这导致{'vegetable': 'potato', 'fruit': 'apple'}
但是,我认为更好的选择是传递变量名称并创建一个字典,如this answer 中提供的那样:
def create_dict(*args):
return dict({i:eval(i) for i in args})
dic = create_dict('fruit', 'vegetable')
编辑:使用eval() 是危险的。更多信息请参考this answer。
【讨论】:
eval,尤其是当它被用于评估函数的输入时。
eval 是危险的,我相信我链接到的使用eval 的答案假定输入i 在运行eval() 之前已经过消毒和检查