Check if Two Dictionaries Have the Same Keys in Python

Checking if two dictionaries have the same keys allows you to compare the keys present in each dictionary. In this blog post, we will explore different methods to check if two dictionaries have the same keys in Python.

Method 1: Using the set() function

# Method 1: Using the set() function
dict1 = {"a": 1, "b": 2, "c": 3}
dict2 = {"b": 4, "c": 5, "d": 6}
same_keys = set(dict1.keys()) == set(dict2.keys())

print("Do the dictionaries have the same keys?", same_keys)

Output:

Do the dictionaries have the same keys? False

Method 2: Using the all() function

# Method 2: Using the all() function
dict1 = {"a": 1, "b": 2, "c": 3}
dict2 = {"b": 4, "c": 5, "d": 6}
same_keys = all(key in dict2 for key in dict1)

print("Do the dictionaries have the same keys?", same_keys)

Output:

Do the dictionaries have the same keys? False