Somethings I create dict from locals() like this:
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
,...
Is it possible to create a class like this:
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. In addition, you can filter out functions by using 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.