DEV Community

Discussion on: Switch case, python?

Collapse
 
vebss profile image
vebss

Is there a reason to use if/else statements over using a dict? I didn't realize switch cases didn't exist in python and I'm curious which the general consensus for it's replacement is

Collapse
 
nati_thinks_tech profile image
Nati Thinks Tech

@vebss
good question!!

Collapse
 
phizzl3 profile image
Brandon

I'm still learning...but I like using dictionaries for instances like this. Maybe something like:

# Dictionary of {selections: values}
plants = {
    1: "Tulip",
    2: "Rose bush",
    3: "Pineapple",
    4: "Banana"
}
# Print options using loop and get selection from user
print("Which seed do you want to buy?")
for entry in plants:
    print(f'{entry}: {plants[entry]}')
selection = int(input("Selection: "))
# Print value from dictionary or message if not found
print(plants.get(selection, "Invalid option."))
Enter fullscreen mode Exit fullscreen mode

There are probably better ways, but this works for me. :)

Thread Thread
 
nati_thinks_tech profile image
Nati Thinks Tech

@Brandon thanks, for this tip! :))