Skip to main content

How to check if two dictionaries have any common keys in Python

How to check if two dictionaries have any common keys in Python.

Here is a step-by-step tutorial on how to check if two dictionaries have any common keys in Python.

Step 1: Define the dictionaries​

Start by defining two dictionaries that you want to compare. Let's call them dict1 and dict2. Make sure they have some common keys.

dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'b': 4, 'c': 5, 'd': 6}

Step 2: Use the keys() method​

In Python, dictionaries have a built-in method called keys() that returns a list of all the keys in the dictionary. We can use this method to get the keys from both dictionaries.

keys1 = dict1.keys()
keys2 = dict2.keys()

Step 3: Check for common keys using the intersection() method​

To check if the dictionaries have any common keys, we can use the intersection() method on the sets of keys. This method returns a new set that contains the common keys between the two sets.

common_keys = keys1.intersection(keys2)

Step 4: Check if there are any common keys​

Finally, we can check if there are any common keys by examining the length of the common_keys set. If the length is greater than 0, it means there are common keys.

if len(common_keys) > 0:
print("The dictionaries have common keys.")
else:
print("The dictionaries do not have any common keys.")

Full code example:​

Here's the full code example that puts it all together:

dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'b': 4, 'c': 5, 'd': 6}

keys1 = dict1.keys()
keys2 = dict2.keys()

common_keys = keys1.intersection(keys2)

if len(common_keys) > 0:
print("The dictionaries have common keys.")
else:
print("The dictionaries do not have any common keys.")

Output:

Running the code will produce the following output:

The dictionaries have common keys.

This indicates that the dictionaries dict1 and dict2 have common keys.