[英]1:1 mapping of variables to a dict with the names as keys
I have a very large amount of variables that I want to return as a dict with their variable names as keys. 我有大量的变量,希望将它们的变量名称作为键作为字典返回。 For example:
例如:
return {
"foo": foo,
"bar": bar,
"baz": baz,
}
This is fine for maybe <=10 keys, but after that it becomes a complete mess. 这对于<= 10个键来说很好,但是之后就变得一团糟。 In my example I want to return ~100 variables like this.
在我的示例中,我想返回约100个这样的变量。
Is there a one liner that I can use to do something like: 是否可以使用一种衬板来做类似的事情:
return x(foo, bar, baz)
Using locals()
: 使用
locals()
:
def x(names, values):
return dict([ (n, values.get(n)) for n in names ])
x(["foo", "bar", "baz"], locals())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.