3

So let's say I have two variables, var and text. I would like to know how I could change the value of text depending on what var is equal to.

For example, i receive var and it's value is "this". I would then like text to get the value 1. If var is then equal to "that", text would then be equal to 2.

I would like not to use if ... elif as there could be quite a lot of values.

Sorry for my english, I could try to re-explain if it's not clear

2
  • What is the problem with if..else ? Commented May 11, 2016 at 7:35
  • Could your please edit your question and include that illustrates your problem? Please also include the code you have tried. Does it work? Commented May 11, 2016 at 7:36

3 Answers 3

6

Use a dict :

yourdict = {'this':1, 'that':2, ...}
text = yourdict[var]
Sign up to request clarification or add additional context in comments.

Comments

4

Use a dictionary to keep the mappings:

check = { 'this': 1, 'that' : 2 }

Then you can use the value dynamically:

text = check.get(var)

Comments

2

Python has no switch/case statement. Best way to go is using a dictionary, which I find more clear even in languages providing a switch statement.

E.g.

cases = {
    'this': 'blah',
    'that': 'blub'
}

var = 'this'
text = cases.get(var, 'your default value here')
print(text)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.