Skip to main content

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

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

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

Step 1: Create two dictionaries

  • Start by creating two dictionaries that you want to compare. You can define them manually or generate them dynamically based on your requirements. For this tutorial, let's consider the following dictionaries:
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'a': 1, 'c': 3}

Step 2: Use the items() method

  • To compare the dictionaries, you need to iterate over the key-value pairs of the smaller dictionary (the potential subset) and check if each key-value pair exists in the larger dictionary. The items() method returns a list of tuples containing the key-value pairs of a dictionary.
for key, value in dict2.items():
if key in dict1 and dict1[key] == value:
continue
else:
print("dict2 is not a subset of dict1")
break
else:
print("dict2 is a subset of dict1")

Step 3: Explanation

  • The for loop iterates over each key-value pair in dict2 using the items() method.
  • Inside the loop, it checks if the current key exists in dict1 and if the corresponding value in dict1 matches the value in dict2.
  • If the condition is satisfied for all key-value pairs in dict2, the else block is executed, indicating that dict2 is a subset of dict1.
  • If any key-value pair doesn't match or if a key doesn't exist in dict1, the else block is skipped, and a message is printed indicating that dict2 is not a subset of dict1.

Step 4: Test the code

  • Finally, you can test the code by running it with different dictionaries to check if one is a subset of the other. Here's an example:
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'a': 1, 'c': 3}

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

Output:

dict2 is a subset of dict1

In this example, dict2 is a subset of dict1 because all the key-value pairs in dict2 also exist in dict1 with the same values.