Problem: Given a dictionary and a key. Can you use the ternary operator to return the key from the dictionary, but only if it exists to avoid the key error? If the key doesn’t exist, a “fall-back” function should be executed.
Example: Say, you want to do something like the following (pseudocode):
var = dict["key"] if dict.has_key("key") else "fallback"
Ternary Operator Short Recap
Ternary Operator: The most basic ternary operator x if c else y
consists of three operands x
, c
, and y
. It is an expression with a return value. The ternary operator returns x
if the Boolean expression c
evaluates to True
. Otherwise, if the expression c
evaluates to False
, the ternary operator returns the alternative y
.
Syntax: The three operands are written as x if c else y
which reads as “return x
if c
else return y
“. Let’s write this more intuitively as:
<OnTrue> if <Condition> else <OnFalse>
Operand | Description |
---|---|
<OnTrue> | The return expression of the operator in case the condition evaluates to True |
<Condition> | The condition that determines whether to return the <On True> or the <On False> branch. |
<OnFalse> | The return expression of the operator in case the condition evaluates to False |
Related article: For a full tutorial on the ternary operator, check out our detailed blog article.
Method 1: Ternary Operator with Membership
Solution: You can use the ternary operator dict[key] if key in dict else "fallback"
to accomplish this:
d = {'Alice': 17, 'Bob': 22} key = 'Alice' # Has key: var = d[key] if key in d else -1 print(var) # 17 # Doesn't have key: key = 'Ann' var = d[key] if key in d else -1 print(var) # -1
The ternary operator returns the value associated to the given key—but only if the key exists. If it doesn’t exist, it returns the default value -1.
Method 2: dict.get(key, default)
However, a more Pythonic way to accomplish the same thing in a more readable and more concise way is to use the dictionary.get(key, default)
function:
d = {'Alice': 17, 'Bob': 22} key = 'Alice' # Has key: var = d.get(key, -1) print(var) # 17 # Doesn't have key: key = 'Ann' var = d.get(key, -1) print(var) # -1
The outer structure of the code is the same—but the get function with default value -1 semantically replaces the more complicated ternary operator.
Try it yourself:
Exercise: Create a more complicated default function that returns the key in reverse order and pass it into the get()
function!
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.