-2

I have a dictionary like this

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

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

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
YASEEN
  • 15
  • 1
  • 3
    Seems like XY problem... What are you actually intending to do? – Austin May 18 '19 at 07:17
  • you can keep function's name (without `()`) instead of string - `dictionary = {"1": abc_123}` and late you can call using `()` - `dictionary["1"]()`. But you have to define function before you use its name in dictionary. – furas May 18 '19 at 07:25

2 Answers2

1

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]

See also:

alvas
  • 115,346
  • 109
  • 446
  • 738
  • If the variable is in the current module [`globals`](https://docs.python.org/3/library/functions.html#globals) is a better solution that `eval` – amirouche May 30 '19 at 14:45
0

You can getattr() functions from their respective package by name, and then call them:

>>> import operator
>>> getattr(operator, "add")
<built-in function add>
>>> getattr(operator, "add")(1, 3)
4

So depending where your functions (e.g. abc_123) are stored, that may help you. But consider storing functions themselves in your dictionary, instead of their names…

I also would suggest you read up on Python functions in more detail.

Jens
  • 8,423
  • 9
  • 58
  • 78