0

I am using nested if in my python code, my example code is :

message = event_data["event"]
    if message.get("subtype") is None :

       if "friday" in message.get('text'):
          callfridayfunction()

       if "saturday" in message.get('text'):
          callsaturdayfunction()

       if "monday" in message.get('text'):
          callmondayfunction()

How can I write this as a switch case or using dictionary ? Please help

wanderors
  • 2,030
  • 5
  • 21
  • 35
  • 1
    What does `message['text']` look like for example? – Jab May 19 '19 at 02:53
  • Possible duplicate of [Replacements for switch statement in Python?](https://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python) – Bharel May 20 '19 at 16:55

1 Answers1

2

This may be the closest to what you want. This will work if multiple days are in the text also.

days_switch = {
    'monday': callmondayfunction,
    'saturday': callsaturdayfunction
    'friday': callfridayfunction
}

message = event_data["event"]
if message.get("subtype") is None :
    text = message.get('text', '')
    days = set(text.split()) & set(days_switch)
    for day in days:
        days_switch[day]()

if you know there aren't multiple days in the text, then the loop isn't needed.

days_switch[set(text.split()) & set(days_switch)]()
Jab
  • 26,853
  • 21
  • 75
  • 114