[英]Most concise way to create a python dictionary from local variables
In Objective-C, you can use the NSDictionaryOfVariableBindings
macro to create a dictionary like this 在Objective-C中,您可以使用
NSDictionaryOfVariableBindings
宏来创建这样的字典
NSString *foo = @"bar"
NSString *flip = @"rar"
NSDictionary *d = NSDictionaryOfVariableBindings(foo, flip)
// d -> { 'foo' => 'bar', 'flip' => 'rar' }
Is there something similar in python? 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. 不,python中的这个快捷方式不存在。
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. 此外,python为这些东西提供了
globals()
和vars()
内置函数。 See the doc . 见文档 。
have you tried vars()
你试过
vars()
vars([object])
瓦尔([对象])
Return the__dict__
attribute for a module, class, instance, or any other object with a__dict__
attribute.返回具有
__dict__
属性的模块,类,实例或任何其他对象的__dict__
属性。Objects such as modules and instances have an updateable
__dict__
attribute;模块和实例等对象具有可更新的
__dict__
属性; however, other objects may have write restrictions on their__dict__
attributes (for example, new-style classes use a dictproxy to prevent direct dictionary updates).但是,其他对象可能对其
__dict__
属性有写限制(例如,新式类使用dictproxy来防止直接字典更新)。
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. Python没有办法做到这一点,虽然它确实有
locals
和globals
函数,可以让你访问整个本地或全局命名空间。 But if you want to pick out selected variables, I consider it better to use inspect
. 但是如果你想挑选出选定的变量,我认为最好使用
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. 确保检查它是否适用于您正在使用的任何Python环境。 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. 不过,如果没有变量名称的引号,我认为没有办法逃脱。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.