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)
>>> if 'lion' in animals:
>>>   print("In dict")
In dict


No comments yet...

Add comment


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.