Aside from storing data, dictionaries and lists can also make it easier to write clean code. They can replace cumbersome if/elif, match/case, and long ‘or’ chains with something simpler.
A list can be used to clean up and replace long chains of or
operators in a boolean expression.
For example, here is statement that prints “I’m flying” when the status (of a presumed airplane) is a phase of flight:
if status == "takeoff" or status == "climb" or status == "cruise" or status == "descent" or status == "landing": print("I'm flying")
To replace the or
chain, we can place all the statuses in a list and then test membership using the in
operator:
flying = ["takeoff", "climb", "cruise", "descent", "landing"] if status in flying: print("I'm flying")
Dictionaries can simplify and replace if/elif chains.
In the next example, a different message is printed for each phase of flight. The if/elif version looks like this:
if status == "takeoff": message = "Zooming down the runway" elif status == "climb": message = "Climbing up with power" elif status == "cruise": message = "Nice and relaxed up here" elif status == "descent": message = "Almost there" elif status == "landing": message = "Touching down"
To simplify this, a you can create a dictionary with status keys and message values. Then, to print the message, simply index the dictionary with the status:
status_messages = {"takeoff": "Zooming down the runway", "climb": "Climbing up with power", "cruise": "Nice and relaxed up here", "descent": "Almost there", "landing": "Touching down"} message = status_messages[status]