How To Check If Key Exists In Dictionary In Python

If you try to retrieve a non-existed key of a dictionary, you are gonna stuck an exception obviously. To be get safer, you should do check its existence before doing any further actions on the item in request. How to check if a key exists in a dictionary?

It’s a piece of cake.

my_models = { 
   "BIOMD0001": { "id": 1, "title": "Test with MongoDB" }, 
   "BIOMD0002": { "id": 2, "title": "Learn ODEs models" }, 
   "BIOMD0003": { "id": 3, "title": "Run the pipeline against the whole database" }
}

The syntax is

def process_model(model_id):
   pass
m_id = "BIOMD0004"
if m_id in my_mnodels:
   process_model(m_id)

Using in operand to check the existence of a specific key in dictionary.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.