-2

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?

3
  • 3
    You don't even need a function, you could just use a dict with string keys d = {'a':'hello', 'b':'hi', 'c':'test'}, then directly look it up with d[key]. Or a list. Commented Jan 24, 2022 at 10:10
  • Are you looking for something like (this)[stackoverflow.com/questions/10773348/…? Here it is described how you get a class attribute when you have its name as a string. This is not precisely what you asked for, but I think it could still help. Commented Jan 24, 2022 at 10:14
  • If you're coming from a Java background, in Python you often don't need the functions and classes to wrap stuff that Java would force you to. As in this case. (and if you absolutely must pass a function here, you can just use dict('a':'hello', 'b':'hi', 'c':'test').get. No need to declare a new function.) Commented Jan 24, 2022 at 13:02

1 Answer 1

1

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]
Sign up to request clarification or add additional context in comments.

6 Comments

dict is a protected word in python I would change to my_dict
This doesn't even need a function call. Just directly look it up with d[key]. We had both independently posted this at the same time.
I didn't say it needed one.. Just seem like OP wanted to use a function @smci
@pugi Changed..
@sagi I didn't say you said it needed one. I just pointed out this is obfuscatory. Often Python learners (esp. coming from Java) are unfamiliar with not needing unnecessary functions and classes. It's helpful to at least point that out to them "You don't need to define a function, you can just do this with dict".
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.