Skip to main content

How to check if a dictionary is a superset of another dictionary in Python

How to check if a dictionary is a superset of another dictionary in Python.

Here's a step-by-step tutorial on how to check if a dictionary is a superset of another dictionary in Python.

Step 1: Understand the concept of a superset

A superset is a set that contains all the elements of another set. In the context of dictionaries, a dictionary is considered a superset if it contains all the key-value pairs of another dictionary.

Step 2: Prepare your dictionaries

Before checking for superset, make sure you have the dictionaries ready. Let's call the dictionaries dict1 and dict2.

dict1 = {"key1": "value1", "key2": "value2", "key3": "value3"}
dict2 = {"key1": "value1", "key3": "value3"}

Here, dict1 is the superset and dict2 is the subset.

Step 3: Use the items() method

To compare dictionaries, we need to iterate over their key-value pairs. The items() method returns a list of tuples containing the key-value pairs of a dictionary.

Step 4: Check for superset

To check if dict1 is a superset of dict2, we can iterate over the key-value pairs of dict2 and check if each pair exists in dict1.

for key, value in dict2.items():
if key not in dict1 or dict1[key] != value:
print("dict1 is not a superset of dict2")
break
else:
print("dict1 is a superset of dict2")

Here, we iterate over the key-value pairs of dict2 using the items() method. For each pair, we check if the key exists in dict1 and if the corresponding value is the same. If any key-value pair is not found or the corresponding values differ, we conclude that dict1 is not a superset of dict2 and break out of the loop. If all key-value pairs are found and their values match, we print that dict1 is a superset of dict2.

Step 5: Test with different dictionaries

You can test the above code with different dictionaries to see if it correctly identifies the superset relationship.

dict1 = {"key1": "value1", "key2": "value2"}
dict2 = {"key1": "value1", "key3": "value3"}

# Output: dict1 is not a superset of dict2
dict1 = {"key1": "value1", "key2": "value2", "key3": "value3"}
dict2 = {"key1": "value1", "key3": "value3"}

# Output: dict1 is a superset of dict2

That's it! You now know how to check if a dictionary is a superset of another dictionary in Python.