Informatics Practices · Ch 4 — Working with Lists and Dictionaries
Membership Operation
Membership Operation
Accessing a missing key with square brackets ends in a KeyError, so a program often needs to check first whether a key exists. That is exactly what the membership operators do on a dictionary — and the crucial point is that they test membership among the keys, not the values.
The in operator checks whether the given key is present in the dictionary. It returns True if the key exists, and False otherwise:
>>> dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}
>>> 'Suhel' in dict1
True
'Suhel' is one of the keys of dict1, so the test answers True.
The not in operator is its exact opposite: it returns True if the key is not present in the dictionary, and False if it is:
>>> dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}
>>> 'Suhel' not in dict1
False
Since 'Suhel' is a key of the dictionary, 'Suhel' not in dict1 evaluates to False. For any key k and dictionary d, k in d and k not in d always give opposite answers.
Membership testing is the safe guard before a lookup: check key in dict1 first (as Program 4-1 did with element in myList before removing it), and you avoid the KeyError that a direct dict1[key] would raise for an absent key. …