Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: Returns a value of variable for a variable that comes as parameter of function

I have a list of statements

a = "hello"
b = "hi"
c= "test"

In a program I got variable name(a,b or c) and need to return value of variable using that function method.

def my_method(item):
     a = "hello"
     b = "hi"
     c= "test"
    

item parameter will be either a , b or c and I need to return value of that item. Is there any technique to return item value without if condition for three statement?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use a dictionary:

my_dict = { "a":"hello", "b":"hi", "c":"test" }

And then

def my_method(item):
    return my_dict[item]

As @smci suggest, it can also be accessed directly without any function

my_dict[item]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading