首页 > 解决方案 > 如何将字符串从python中的字典转换为变量名

问题描述

我有一本这样的字典

dictionary = {"1":"abc_123","2":"def_456" "3":"ghi_789"}

所以我想转换"abc_123"为a abc_123,因为我有一个函数调用abc_123,有人可以帮助我吗?

标签: pythonpython-2.7

解决方案


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]

也可以看看:


推荐阅读