Which operator is used in Python to directly check whether a key exists in a…
2024
Which operator is used in Python to directly check whether a key exists in a dictionary?
- A.
find() operator
- B.
search() method
- C.
in operator
- D.
index() method
- E.
contains() function
Attempted by 8 students.
Show answer & explanation
Correct answer: C
Concept
Python provides the membership-test operator in to ask whether a value is present in a container. When the container is a dictionary, in tests the dictionary's keys (not its values), and evaluates to a Boolean — True if the key is present, False otherwise.
Application
Given a dictionary d = {'a': 1, 'b': 2}, a direct key-existence check is written as a single expression:
'a' in d # -> True
'z' in d # -> FalseThis is the idiomatic, built-in way to check for a key. It runs in average O(1) time because a dict is a hash table, and it needs no method call.
Contrast
find()/index(): these are sequence (string/list) methods for locating a substring or element by position; dictionaries do not define them.search(): belongs to theremodule for regular-expression matching, not to dictionaries.contains(): there is no built-incontains()function; the underlying hook is the dunder__contains__, whichincalls for you — you do not invoke it directly.
Hence the membership operator in is the correct way to directly check whether a key exists in a dictionary.