Python Dictionary - in operator

Check whether an item is present in a Python Dictionary object with the in operator

Dictionary Updated 10 Sep 2016 1 min read

Membership operator - "in"

  • The in operator called on a dictionary instance tests whether a given key is present in a dictionary.
  • If the value is present in the sequence it returns True. It returns False otherwise.
  • The behaviour of in operator is the opposite of the not in operator.

Example 1

python
# Example Python program that finds

            # whether an element is present in a dictionary

            # using the "in" operator

            d1 = {"if":1, "else":2, "for":3, "while":4}

            token     = "switch"

            if token in d1:

                print("Token with value \"%s\" is found"%token)

            else:

                print("Token with value \"%s\" is not found"%token)

Output

Output
Token with value "switch" is not found

Example 2

python
# Example Python program that checks

            # the presence of a key in a dictionary

            # element

fruitPrices = {"Apples":1.42,

                            "Oranges":1.33,

                            "Kiwi":2.54,

                            "Avocados":6.1,

                            "Strawberries":1.7};

fruit2Lookup = "Grapes";

if fruit2Lookup in fruitPrices:

                print("Yes, %s are available"%fruit2Lookup);

            else:

                print("%s not available"%fruit2Lookup);

Output

Output
Grapes not available