[英]Elegant way to create dict from local variables in Python
Somethings I create dict from locals() like this:我从 locals() 创建 dict 的东西是这样的:
var1 = 1
var2 = 2
var3 = 3
...
my_dict = dict(
var1=var1,
var2=var2,
var3=var3,
...
)
Or:或者:
var1 = 1
var2 = 2
var3 = 3
...
keys = 'var1 var2 var3 ...'.split()
my_dict = {k: v for k, v in locals().items() if k in keys}
Note: keys not only var1
, var2
, var3
, may also be foo
, key
,...注意:键不仅是
var1
, var2
, var3
,还可能是foo
, key
,...
Is it possible to create a class like this:是否可以像这样创建 class :
class LocalDict(dict):
...
LocalDict('var1 var2 var3') == dict(var1=var1, var2=var2, var3=var3)
It all depends on the way you need to work with the data, really.实际上,这完全取决于您处理数据所需的方式。 Your methods above are sound, especially the dict comprehension.
您上面的方法是合理的,尤其是听写理解。 So other than the old-fashioned way:
所以除了老式的方式:
{"key": "value", ... }
I'd say you're doing it right.我会说你做得对。 If you have a specific example, you can edit your question and I will try to work off that.
如果你有一个具体的例子,你可以编辑你的问题,我会试着解决这个问题。
Hope that helps!希望有帮助!
How about this?这个怎么样?
var1 = 1
var2 = 2
var3 = 3
my_dict = {k: v for k, v in locals().items() if k.startswith('var')}
or或者
var1 = 1
var2 = 2
var3 = 3
var4 = "abc"
my_dict = {k: v for k, v in locals().items() if isinstance(v, int) or isinstance(v, str)}
Since all the built-in members of locals()
starts and ends with __
, you can filter them out by these prefix and suffix.由于
locals()
的所有内置成员都以__
开头和结尾,因此您可以通过这些前缀和后缀将它们过滤掉。 In addition, you can filter out functions by using callable
:此外,您可以使用
callable
过滤掉函数:
For example:例如:
a = 1
b = 2
output = {k:v for k,v in locals().items() if not (k.startswith("__") and k.endswith("__")) and not callable(v)}
print(output) # output: {'a': 1, 'b': 2}
After trying a lot, the following code is nearly what I want:经过大量尝试,以下代码几乎是我想要的:
class LocalDict(dict):
def __new__(cls, spaces, attrs):
return {k: v for k, v in spaces.items() if k in attrs.split()}
def foo():
a = 1
b = c = 2
my_dict = LocalDict(locals(), 'a b c')
return my_dict
print(foo()) # {'a': 1, 'b': 2, 'c': 2}
And I wonder whether there is some way that I don't need to pass locals
to the LocalDict
class.而且我想知道是否有某种方法不需要将
locals
传递给LocalDict
class。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.