从局部变量创建python字典的最简洁方法

2024-09-20 03:54:09 发布

您现在位置:Python中文网/ 问答频道 /正文

在Objective-C中,可以使用NSDictionaryOfVariableBindings宏来创建这样的字典

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

python中有类似的东西吗?我经常发现自己在写这样的代码

^{pr2}$

做这样的事有捷径吗?在

d = dict(foo, flip) # -> {'foo': 'bar', 'flip': 'rar'}

Tags: 代码字典foobardict捷径rarobjective
3条回答

你试过^{}

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).

所以

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

Python没有办法做到这一点,尽管它有函数locals和{},它们可以让您访问整个本地或全局命名空间。但是如果您想选择所选的变量,我认为最好使用inspect。这里有一个函数可以为您做到这一点:

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

确保检查它在您使用的任何Python环境中都能正常工作。用法如下:

^{pr2}$

不过,我不认为没有任何方法可以在变量名周围加引号。在

不,python中不存在此快捷方式。在

但也许这就是你需要的:

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

另外,python为这类事情提供了globals()和{}的内置函数。 参见doc。在

相关问题 更多 >