Python dictionaries allow you to store values in a key-value format.
You can return a default value if a key is not available in the dictionary using yourdict.get(“key”, default_value)
statement in Python.
Basic Example
yourdict = {
"one": 1,
"two": 2,
"three": 3,
"four": 4
}
yourdict.get("five", 5)
Output
5
This tutorial teaches you how to return a default value if a key is not available in the dictionary and what other cases need to be considered when returning the default values.
Sometimes key might be available but with a None
value or a missing value. Let us learn how to handle such scenarios.
Table of Contents
Using Dict.get
The dictionary.get() method returns the value of the key if it exists or the default value when the key is not available in the dictionary.
The get()
method accepts two parameters.
- key – The key to fetch the value for.
- [default value] – Optional – A Value to return when the key is not available in the dictionary
Return Value
The value of the key.
- If the key is NOT present, and the default value is NOT specified,
None
will be returned - If the key is NOT present and the default value is specified, then the default value will be returned
Code
- Key five is not available in the dictionary. Hence the default value
5
passed to theget()
method is returned.
yourdict = {
"one": 1,
"two": 2,
"three": 3,
"four": 4
}
yourdict.get("five", 5)
Output
5
Handling Keys With None Value Using IF
Sometimes a dictionary key might contain a None
value for a key.
In this case, passing the default value to the get()
method doesn’t make a difference.
Only None
will be returned. Because the default value is returned only when the key is unavailable.
Code
The value None is returned in the following code because the key five has the value None
.
yourdict = {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": None
}
result = yourdict.get("five", 5)
print(result)
Output
None
- To handle this, you can check if the dictionary key is empty after getting it.
- Use an
if
statement to check if the result isNone
and assign a value accordingly.
Code
The following code demonstrates how to use an if
statement to assign a default value if the result is None
.
result = 5 if result is None else result
print(result)
Output
5
Handling Keys With None Value Using Boolean OR Operator
This is an alternate approach to handling keys with a None
value.
Use the OR
operator and pass a default value.
- if the result is a
falsy
value such asNone
, then the value passed with OR will be returned.
You must be careful because some dictionary keys might contain a Falsy value such as 0
. In that case also, the alternate default value will be used.
Code
The following code demonstrates how to use the OR operator with the dict.get()
method.
yourdict = {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": None
}
result = yourdict.get('five', 5) or 5
print(result)
Output
5