python - 如何将字符串从python中的字典转换为变量名
问题描述
我有一本这样的字典
dictionary = {"1":"abc_123","2":"def_456" "3":"ghi_789"}
所以我想转换"abc_123"
为a abc_123
,因为我有一个函数调用abc_123
,有人可以帮助我吗?
解决方案
TL;博士
# You have two functions.
>>> abc = lambda x: x**2
>>> xyz = lambda x: x**3
>>> type(abc), type(xyz)
(<class 'function'>, <class 'function'>)
# You have a key-value map of the names of the functions.
>>> d = {'1':'abc', '2':'xyz'}
>>> type(d['1'])
<class 'str'>
# Convert them into a key-value map of the index and the actual function.
>>> func_d = {k:eval(v) for k,v in d.items()}
>>> func_d[1]
也可以看看:
推荐阅读
- html - nodejs发送文件html页面
- scala - 避免重新编译 Scalas 脚本
- javascript - 异步函数返回一个promise。如何使promise 值全局化?
- r - 重现 Stata 汇总的 OLS 结果
- python - 我可以在离线的 Windows PC 上安装 Anaconda 吗?
- java - 登录 Spring MVC 应用程序时的自定义响应
- java - 带有类对象的未处理异常类型 ParseException
- typo3 - 带有 UserFunc 的 TYPO3 TCA 标签 - 如何获取 HTML 格式的标签?
- rust - 为什么 centos 在 dylib build 中包含额外的依赖项
- email - 为什么来自 web ui 和 python 代码的电子邮件内容彼此不同?