首页 > 解决方案 > 使用 Python 从 JavaScript `{ var1, var2, ...}` 等局部变量创建字典

问题描述

a=1;
obj={ a }  // JSON.stringify(obj) == '{"a":1}'

这使得objhas 键a和它的值是1

a = 1
obj = { 'a': a }

是否可以创建一个函数或类来编写这样的代码?

a = 1
obj = func_or_class(a)  # obj == {'a': 1}

标签: pythondictionary

解决方案


由于所有的内置成员都以locals()开头和结尾__,因此您可以通过这些前缀和后缀将它们过滤掉。此外,您可以使用以下方法过滤掉函数callable

例如:

a = 1
b = 2
output = {k:v for k,v in locals().items() if not (k.startswith("__") and k.endswith("__")) and not callable(v)}
print(output) # output: {'a': 1, 'b': 2}

推荐阅读