如何将字符串从python中的字典转换为变量名 [英] How to convert string into variable name from dictionary in python

查看:27
本文介绍了如何将字符串从python中的字典转换为变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本这样的字典

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

所以我想将 "abc_123" 转换为 abc_123 因为我有一个函数调用 abc_123,谁能帮我.

so I want to convert "abc_123" as a abc_123 because I have a function call abc_123, can anyone help me please.

推荐答案

TL;DR

# 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]

另见:

这篇关于如何将字符串从python中的字典转换为变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆