-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?

Himal Acharya
  • 836
  • 4
  • 14
  • 24
  • 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. – smci Jan 24 '22 at 10:10
  • Are you looking for something like (this)[https://stackoverflow.com/questions/10773348/get-python-class-object-from-string]? 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. – NerdOnTour Jan 24 '22 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.) – smci Jan 24 '22 at 13:02

1 Answers1

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]
sagi
  • 40,026
  • 6
  • 59
  • 84
  • 1
    `dict` is a protected word in python I would change to `my_dict` – pugi Jan 24 '22 at 10:12
  • 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. – smci Jan 24 '22 at 10:12
  • 1
    I didn't say it needed one.. Just seem like OP wanted to use a function @smci – sagi Jan 24 '22 at 10:13
  • @pugi Changed.. – sagi Jan 24 '22 at 10:13
  • @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"*. – smci Jan 24 '22 at 10:28
  • I agree, that's why I edited my answer.. :) – sagi Jan 24 '22 at 10:29