[英]elegant way to fill dictionary with variables in python
I'm searching for an elegant more generic way to fill a dictionary with variables: 我正在寻找一种用变量填充字典的更优雅的通用方法:
dic = {}
fruit = 'apple'
vegetable = 'potato'
dic['fruit'] = fruit
dic['vegetable'] = vegetable
is there a more generic way without using the variable-name in quotes ? 有没有在引号中使用变量名的更通用的方法?
If the quotes are the problem, how about this? 如果引号是问题,那怎么办?
fruit = 'apple'
vegetable = 'potato'
dic = dict(
fruit = fruit,
vegetable = vegetable
)
May not be a very elegant solution but you could use locals()
for retrieving the variables and then convert them into a dictionary. 可能不是一个很好的解决方案,但是您可以使用
locals()
检索变量,然后将其转换为字典。
fruit = 'apple'
vegetable = 'potato'
dic = {key:value for key, value in locals().items() if not key.startswith('__')}
This results in {'vegetable': 'potato', 'fruit': 'apple'}
结果为
{'vegetable': 'potato', 'fruit': 'apple'}
However, I believe a better option would be to pass the variable names and create a dictionary as provided in this answer : 但是,我相信一个更好的选择是传递变量名并创建一个字典,如以下答案所示 :
def create_dict(*args):
return dict({i:eval(i) for i in args})
dic = create_dict('fruit', 'vegetable')
Edit: Using eval()
is dangerous. 编辑:使用
eval()
是危险的。 Please refer to this answer for more information. 请参考此答案以获取更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.