python - 使用 Python 从 JavaScript `{ var1, var2, ...}` 等局部变量创建字典
问题描述
- 对于 JavaScript,可以通过以下方式创建对象
a=1;
obj={ a } // JSON.stringify(obj) == '{"a":1}'
这使得obj
has 键a
和它的值是1
- 对于 Python 代码是:
a = 1
obj = { 'a': a }
是否可以创建一个函数或类来编写这样的代码?
a = 1
obj = func_or_class(a) # obj == {'a': 1}
解决方案
由于所有的内置成员都以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}
推荐阅读
- azure - 为组重复创建请求:Azure AD SCIM 预配
- vue.js - 在 nuxtjs 中刷新页面后如何保持用户身份验证?
- python - 如何将字典字典分配给机器人文件中的变量
- powerapps - 如何使用 Canvas 应用程序在特定时间(而非计划)触发 Power 自动化流程?
- ios - React-Native-共享菜单 | 错误:在 M1 Macbooks 上找不到提供程序
- flutter - 为什么 snapshot.data.length 有错误?
- prisma - 如何在运行时更改 PrismaClient 数据库连接?
- linux - 合并和排序日志文件 - 多行
- linux - 在换行中显示字符串的每个字符的 Linux / UNIX 命令是什么?
- reactjs - React JS 中的长度转换器 反应原生