5. Check keys
The in operator checks whether a key exists in a dictionary:
It is an operator, not a method. It looks only at the keys, never at the values:
not in is the opposite:
The check is case-sensitive and exact: "Name" and "name" are different keys.
Coming from JavaScript? key in d checks the dict's own keys only. JS key in obj also walks the prototype chain, so the two are not equivalent for objects.
Check for an existing key
Create person = {"name": "Ada", "age": 36}. Print whether "name" is a key of person using in.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Check for a missing key
With the same person = {"name": "Ada", "age": 36}, print whether "email" is a key of the dictionary.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Values are not keys
in checks keys only. With person = {"name": "Ada", "age": 36}, print whether "Ada" is in the dictionary. "Ada" is a value, not a key, so the result is False.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Use not in
not in is the opposite of in. With person = {"name": "Ada", "age": 36}, print whether "email" is not a key of the dictionary.
Print exactly:
Create a free account to save your progress and unlock chapter 2.