The shortest way to create a python dictionary from local variables

In Objective-C, you can use the NSDictionaryOfVariableBindings macro to create such a dictionary

 NSString *foo = @"bar" NSString *flip = @"rar" NSDictionary *d = NSDictionaryOfVariableBindings(foo, flip) // d -> { 'foo' => 'bar', 'flip' => 'rar' } 

Is there something similar in python? I often find that I write code like this

 d = {'foo': foo, 'flip': flip} # or d = dict(foo=foo, flip=flip) 

Is there a shortcut to do something like this?

 d = dict(foo, flip) # -> {'foo': 'bar', 'flip': 'rar'} 
+4
source share
3 answers

Have you tried vars()

vary ([object])
Returns the __dict__ attribute for a module, class, instance, or any other object with the __dict__ attribute.

Objects, such as modules and instances, have an updated __dict__ attribute; however, other objects may have write restrictions for their __dict__ (for example, new-style classes use dictproxy to prevent direct dictionary updates).

So

 variables = vars() dictionary_of_bindings = {x:variables[x] for x in ("foo", "flip")} 
+3
source

No, this shortcut does not exist in python.

But maybe this is what you need:

 >>> def test(): ... x = 42 ... y = 43 ... return locals() >>> test() {'y': 43, 'x': 42} 

In addition, python provides globals() and vars() built-in functions for such things. See doc .

+4
source

Python has no such way to do this, although it does have locals and globals functions that can give you access to the entire local or global namespace. But if you want to select the selected variables, I find it better to use inspect . Here is the function that should do this for you:

 def compact(*names): caller = inspect.stack()[1][0] # caller of compact() vars = {} for n in names: if n in caller.f_locals: vars[n] = caller.f_locals[n] elif n in caller.f_globals: vars[n] = caller.f_globals[n] return vars 

Make sure it works in any Python environment that you use. Usage will be as follows:

 a = 1 b = 2 def func(): c = 3 d = 4 compact('b', 'd') # returns {'b': 2, 'd': 4} 

I donโ€™t think there is a way to escape without quotes around variable names.

+3
source

Source: https://habr.com/ru/post/1438356/


All Articles