简体   繁体   中英

How to write switch case in python with dictionary

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

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)]()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM