Write Shorter Conditionals (Using Dictionaries) | Python Snippets #4

preview_player
Показать описание
In the "Python Snippets" series we will cover a variety of topics around Python programming in a byte-sized format.

Each video covers a single topic that you might or might not be familiar with, and is meant to be a hands-on part of your road to being a better Python programmer.

This week: I'll teach you how to write shorter conditionals using dictionaries!

VIDEO CONTENT
---------------------------------------------------
0:00 - Intro
0:16 - Benefits and drawbacks
0:36 - Example case
0:50 - Using If-Else and Match-Case
1:10 - Dictionary Conditional
2:02 - Speed Comparison (1)
2:33 - Speed Comparison (2)

CREDITS
---------------------------------------------------
Introduction Audio: Dion P. van der Geest
Background Audio: Royalty Free Music from Bensound

Sign icon: Kiranshastry (from Flaticon)
Checkmark icon: Octopocto (from Flaticon)
Stop & Thumbs Down Icon: Freepik (from Flaticon)

Dictionary photo: Mega Pixel, Shutterstock
Рекомендации по теме
Комментарии
Автор

For this month example, declaring the dictionary as a global constant is the correct approach in my view. It is external and constant data that does not change. Perhaps this would all be better wrapped as a class, or passing a config object which has the dictionary declared as a member if it helps with encapsulation which ensures we do not redeclare the dictionary each time.

appuser
Автор

I love the .get() method and how you can give a second arg as a fallback value. I'm curious though, how are you measuring the runtime? Those numbers seem a bit unrealistic. Maybe I'm missing something?

cwatson
Автор

You can also memoize the dict if you want to keep it in the function

dang
Автор

Note that what you have here is not a switch statement, but a switch _expression_ . You have something you can use inside an expression, which is not true of if-statements and match-statements.

Did you try it in the lazy-evaluation form?

{
key1 ∶ lambda ∶ case_key1_expr,
key2 ∶ lambda ∶ case_key2_expr,
key3 ∶ lambda ∶ case_key3_expr,
․․․
}․get(index, default_expr)]()

lawrencedoliveiro
Автор

Thijmen,
There's an even faster (although not generic) solution:

def month(idx):
try:
return ("Not a month", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")[(idx >= 1) and idx]
except Exception:
return "Not a month"

Without the check for negative and non integer values it is very elegant, IMHO:

def month(idx):
return ("Not a month", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")[idx]

ruudvanderham
Автор

I think you can also use an Enum instead of a dict

federicomuciaccia
Автор

Why not use the built in functions of datetime:

import datetime

#provide month number
month_num = "3"
datetime_object = datetime.datetime.strptime(month_num, "%m")

month_name =
print("Short name: ", month_name)

full_month_name =
print("Full name: ", full_month_name)

Simple_Simon_UK
Автор

Why to declare de dict outside is faster?

miguelvasquez
Автор

make it even faster :
_get_month = dt.get
def month(idx):
return _get_month(idx, "not a month")

abdelghafourfid
visit shbcf.ru