Example of how to check if a key is in a dictionary in python 3 ?
Table of contents
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
Liens | Site |
---|---|
operator — Standard operators as functions | doc python |
Check if a given key already exists in a dictionary | stackoverflow |