Check If a Dictionary is a Subset or Superset of Another Dictionary in Python

Checking if a dictionary is a subset or superset of another dictionary allows you to compare the keys and values of two dictionaries. In this blog post, we will explore different methods to check if a dictionary is a subset or superset of another dictionary in Python.

Method 1: Using the items() method

# Method 1: Using the items() method
dict1 = {"name": "John", "age": 30}
dict2 = {"name": "John", "age": 30, "city": "New York"}
is_subset = dict1.items() <= dict2.items()
print("Is Subset:", is_subset)

Output:

Is Subset: True

Method 2: Using the keys() method

# Method 2: Using the keys() method
dict1 = {"name": "John", "age": 30}
dict2 = {"name": "John", "age": 30, "city": "New York"}
is_subset = dict1.keys() <= dict2.keys()
print("Is Subset:", is_subset)

Output:

Is Subset: True