在Objective-C中,您可以使用NSDictionaryOfVariableBindings宏来创建这样的字典
NSString *foo = @"bar"
NSString *flip = @"rar"
NSDictionary *d = NSDictionaryOfVariableBindings(foo, flip)
// d -> { 'foo' => 'bar', 'flip' => 'rar' }
Run Code Online (Sandbox Code Playgroud)
python中有类似的东西吗?我经常发现自己编写这样的代码
d = {'foo': foo, 'flip': flip}
# or
d = dict(foo=foo, flip=flip)
Run Code Online (Sandbox Code Playgroud)
有这样做的快捷方式吗?
d = dict(foo, flip) # -> {'foo': 'bar', 'flip': 'rar'}
Run Code Online (Sandbox Code Playgroud)
不,python 中不存在这个快捷方式。
但也许这就是您所需要的:
>>> def test():
... x = 42
... y = 43
... return locals()
>>> test()
{'y': 43, 'x': 42}
Run Code Online (Sandbox Code Playgroud)
此外,Python 还提供了globals()此类vars()功能的内置函数。请参阅文档。
你有没有尝试过vars()
vars([object])
返回__dict__模块、类、实例或任何其他具有__dict__属性的对象的属性。模块和实例等对象具有可更新的
__dict__属性;但是,其他对象可能对其__dict__属性有写限制(例如,新式类使用 dictproxy 来防止直接更新字典)。
所以
variables = vars()
dictionary_of_bindings = {x:variables[x] for x in ("foo", "flip")}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2113 次 |
| 最近记录: |