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?

  1. A.

    find() operator

  2. B.

    search() method

  3. C.

    in operator

  4. D.

    index() method

  5. 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      # -> False

This 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 the re module for regular-expression matching, not to dictionaries.

  • contains(): there is no built-in contains() function; the underlying hook is the dunder __contains__, which in calls 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.

Explore the full course: Ibps So It Mains

Loading lesson…