You can create the function or use the get() method to return a default value if Key is not in Dictionary in Python. Let’s check out the details below to get more information.
Return a default value if Key is not in Dictionary in Python
Create the function to return a default value if Key is not in Dictionary
Example:
In this example, then create the function to check if a key exists in the Dictionary. If it exists, display the value of that Key. If not found, display the default value assigned as None. View the code example below to get more information.
notification = { "alert": "Welcome to Learn and Share IT", "message": "Nice to meet you." } def checkKey(key, dictionary): if key in dictionary: print(dictionary[key]) else: print("None") # Set the default value is None if key not exist in dictionary checkKey("alert", notification) checkKey("message", notification) checkKey("notify", notification) # Expected output is None
Output
Welcome to Learn and Share IT
Nice to meet you
None
Use the get() method
The get() method returns the value of the item with the specified Key.
Syntax:
dictionary.get(keyname, value)
Parameters:
- keyname: The key name of the item you want to return a value for.
- value: The value to return. The default value is none.
Return value: The return value is the value of an item of Key.
Example:
In this example, we will use a more straightforward way is the get() method. We call the get() method to check if the Key exists in the Dictionary. If it exists, then return the value of that Key. Otherwise, return the value in the 2nd argument as None.
notification = { "alert": "Welcome to Learn and Share IT", "message": "Nice to meet you." } print(notification.get("message", "None")) print(notification.get("alert", "None")) print(notification.get("notify", "None")) # Expected output is None
Output:
Welcome to Learn and Share IT
Nice to meet you
None
Summary
In this tutorial, we have explained how to return a default value if Key is not in Dictionary in Python by using two methods. We always hope this tutorial is helpful to you. Leave your comment here if you have any questions or comments to improve the article. Thanks for your read.
Maybe you are interested:

My name is Fred Hall. My hobby is studying programming languages, which I would like to share with you. Please do not hesitate to contact me if you are having problems learning the computer languages Java, JavaScript, C, C#, Perl, or Python. I will respond to all of your inquiries.
Name of the university: HUSC
Major: IT
Programming Languages: Java, JavaScript, C , C#, Perl, Python