How to check if a dictionary has a given key in python 3 ?

Published: October 18, 2020

Tags: Python;

DMCA.com Protection Status

Example of how to check if a key is in a dictionary in python 3 ?

Check if a key exists in a dictionary

Let's consider the following python dictionary :

customers_dic = {'Bob':[24,'M'],
                 'John':[37,'M'],
                 'Anna':[42,'F']}

to check if a key for example 'John' is in the dictionary customers_dic. a solution is to use the operator in

'John' in customers_dic

returns

True

While

'Louise' in customers_dic

returns

False

Create a condition with if

It is then possible to use if to do something if and only if the key is in the dictionary, example:

if 'Anna' in customers_dic:
    print(customers_dic['Anna'][0])

returns

42

Références