In Objective-C, you can use the NSDictionaryOfVariableBindings
macro to create a dictionary like this
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 myself writing 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'}
No, this shortcut in python does not exist.
But perhaps this is what you need:
>>> def test():
... x = 42
... y = 43
... return locals()
>>> test()
{'y': 43, 'x': 42}
Also, python provides globals()
and vars()
build-in functions for such things. See the doc .
have you tried vars()
vars([object])
Return the__dict__
attribute for a module, class, instance, or any other object with a__dict__
attribute.Objects such as modules and instances have an updateable
__dict__
attribute; however, other objects may have write restrictions on their__dict__
attributes (for example, new-style classes use a dictproxy to prevent direct dictionary updates).
so
variables = vars()
dictionary_of_bindings = {x:variables[x] for x in ("foo", "flip")}
Python doesn't quite have a way to do this, though it does have the functions locals
and globals
which can give you access to the entire local or global namespace. But if you want to pick out selected variables, I consider it better to use inspect
. Here's a function that should do that 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 to check that it works in whatever Python environment you're using. Usage would be like so:
a = 1
b = 2
def func():
c = 3
d = 4
compact('b', 'd') # returns {'b': 2, 'd': 4}
I don't think there's any way to get away without the quotes around the variable names, though.
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.