Skip to content

Python not in dictionary

  • by

In Python, the not in keyword is used to check whether a key or value is present in a dictionary or any other iterable. It is typically used in combination with the in keyword to perform membership tests.

For dictionaries, you can use not in to check if a specific key is not present in the dictionary. Here’s the general syntax:

if key not in dictionary:
    # Do something if the key is not present in the dictionary

Similarly, you can use not in to check if a value is not present in the dictionary. However, for this case, you need to use the .values() method to access the values of the dictionary and perform the membership test. Here’s how you can do it:

if value not in dictionary.values():
    # Do something if the value is not present in the dictionary

Python not in dictionary example

Simple example code.

# Sample dictionary
my_dict = {'apple': 2, 'banana': 3, 'orange': 1}

# Check if 'apple' is not a key in the dictionary
if 'apple' not in my_dict:
    print("'apple' is not present as a key")

# Check if 'grapes' is not a key in the dictionary
if 'grapes' not in my_dict:
    print("'grapes' is not present as a key")

# Check if the value 5 is not present in the dictionary
if 5 not in my_dict.values():
    print("The value 5 is not present")

# Check if the value 3 is not present in the dictionary
if 3 not in my_dict.values():
    print("The value 3 is not present")

Output:

Python not in dictionary

As you can see, the not in keyword helps you check for the absence of keys or values in a dictionary.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading