-3
d1 = {
        "a": "test"
    }
    
    cmd_dict = {
        "cmd1": "d1['a']",
        "cmd2 : "os.getcwd()"
    }
value = eval(md_dict['cmd1]) 
print(value)

Not i will get the value as test.

I am getting pylint error W0123 becasue i am using eval. is there any way to perform the same without using eval.

Samwise
  • 68,105
  • 3
  • 30
  • 44
SS L
  • 5
  • 2

1 Answers1

1

Put functions in your dictionary, and you can simply call them like any other function. No eval() needed:

import os

d1 = {}
    
cmd_dict = {
    "cmd1": lambda: d1['a'],
    "cmd2" : os.getcwd,
}

d1['a'] = 'test'

value = cmd_dict['cmd1']()
print(value)  # test

Note that lambda creates a small anonymous function that will evaluate and return d1['a'] when it's called; the delayed evaluation (which, again, you do not need eval() to do) is why it returns test even though that value is set in d1 after cmd_dict has been created.

Samwise
  • 68,105
  • 3
  • 30
  • 44
  • thank you very much for the info..sorry i have one further question..if i have all the json data in cmd.json() file..is there any way to specify lambda inside json file cmd_dict = { "cmd1": lambda: d1['a'], "cmd2" : os.getcwd, } Exampl {"cmd1": lambda : d1[a] } – SS L Jun 01 '23 at 06:02
  • No -- you probably want to create a Python module rather than putting Python source code inside a JSON file. – Samwise Jun 01 '23 at 06:10