Check if a key exists in a dictionary | Python

/ #Python


To prevent errors, we sometimes want to check if a key exists in a Python dictionary. Here's how you do that.

Example of Python dictionary

>>>> animals = {'lion': 'carnivore', 'giraffe': 'herbivore'}
>>> print('lion' in animals)
True
>>> if 'lion' in animals:
>>>   print("In dict")
In dict

Comments

No comments yet...

Add comment

Info

Please log in to comment!

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.