Easy Tutorial
❮ Python Bubble Sort Ref Set Difference ❯

Python3 Dictionary in Operator

Python3 Dictionary


Description

The Python dictionary in operator is used to check if a key exists in the dictionary. If the key is in the dictionary dict, it returns true; otherwise, it returns false.

The not in operator is the opposite: if the key is in the dictionary dict, it returns false; otherwise, it returns true.

Syntax

Syntax for the in operator:

key in dict

Parameters

Return Value

Returns true if the key is in the dictionary, otherwise returns false.

Example

The following example demonstrates the use of the in operator in a dictionary:

Example (Python 3.0+)

#!/usr/bin/python3

thisdict = {'Name': 'tutorialpro', 'Age': 7}

# Check if the key 'Age' exists
if 'Age' in thisdict:
    print("Key 'Age' exists")
else:
    print("Key 'Age' does not exist")

# Check if the key 'Sex' exists
if 'Sex' in thisdict:
    print("Key 'Sex' exists")
else:
    print("Key 'Sex' does not exist")

# not in

# Check if the key 'Age' does not exist
if 'Age' not in thisdict:
    print("Key 'Age' does not exist")
else:
    print("Key 'Age' exists")

The output of the above example is:

Key 'Age' exists
Key 'Sex' does not exist
Key 'Age' exists

Python3 Dictionary

❮ Python Bubble Sort Ref Set Difference ❯