Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

switch-case statement for STRINGS in Python

I need to do something similar to the CASE WHEN .. OR .. THEN from SQL in python for STRINGS. For example, if I say "DOG" or "CAT".. my translation is "ANIMAL".

I don't want to use IF ELIF ELIF..

The only solution that i can see is:

l = ['cat','dog', 'turttle']
d = {'animal': ['cat','dog', 'turttle']}
word = 'cat'
if word in l:
    for i, j in d.iteritems():
        if word in j:
            print i
        else:
            print word

animal

It works but it seems very ugly..

Any other solution?

THANKS!

like image 799
Gonzalo AB Avatar asked Aug 17 '18 13:08

Gonzalo AB


2 Answers

For your purpose I would suggest that you go with a dict indexed by the name of the animal instead. The list l in your code would then also be redundant because it's simply the keys of this dict.

d = {
    'cat': 'animal',
    'dog': 'animal',
    'turtle': 'animal'
}
word = 'cat'
print(d.get(word, word))
like image 117
blhsing Avatar answered Nov 07 '22 05:11

blhsing


You can do in this way:

animal_list = ['cat','dog', 'turttle']
plant_list = ['tree', 'grass']
d = {'animal': animal_list, 'plant': plant_list}
word = 'tree'
for key, value in d.iteritems():
    if word in value:
        print key
like image 25
Joe Avatar answered Nov 07 '22 04:11

Joe