Find the Common Keys from two Dictionaries in Python


The dictionary is one of the four data types in Python that doesn’t allow any key duplicates. In this problem statement, we have to create two dictionaries as user input and check the matches for a common key. If key elements are found as common then it prints the result. This can be possible by using various methods in Python such as type(), items(), set(), etc.

Let’s take an example of this:

Input:

A = { ‘I’: 10, ‘II’: 20, ‘III’: 30, ‘IV’:40 }

B = { ‘II’: 40, ‘V’: 60, ‘VI’: 80, ‘I’: 90 }

Output:

{ ‘I’, ‘II’ }

Explanation:

Above two variables are defined to set the input values of the dictionary and as per the problem statement it is found that the Keys names− I and II match in both variables.

Syntax

The following syntax is used in the examples-

keys()

The keys() is a built−in method in Python that helps to return the key from the dictionary.

items()

This is the built−in method in Python that returns the view object by containing key with value pair.

set()

The set() is an in−built method in Python that can be used to store multiple items in a single variable.

filter()

The filter() method is applied when we need to filter the items based on specific conditions. In simple terms, it allows users to iterate those elements that are extracted to satisfy the condition.

lambda

This lambda function in Python is known as an anonymous function. It can be used when function objects are required.

intersection()

The intersection is a built−in method in Python that checks the similarity between two different sets.

Using keys() function

The program uses keys to return the key from the dictionary if key elements are found to be the same.

Example

In the following example, start the program by defining the function named key_common that accepts two parameters− a( receive the value from dict_1 ) and b( receive the value from dict_2 ). Then use the nested for loop to iterate each and individual dictionary i.e. a and b through variables i and j by using built−in function keys(). Next, using an if−statement it will check the equivalency of variables− i and j which will find a similar match and return the unique key by printing the variable i. Now create the two variables− dict_1 and dict_2 to declare the dictionary. Then use the function call to get the result.

def key_common(a,b):
      for i in a.keys():
        for j in b.keys(): 
          if i==j:
            print(i ,"is identified as the common key")
dict_1 ={'A':20,'T':30,'W':40,'S':100,'E':80}
dict_2 ={'E':200,'B':450,'S':100,'S':55,'A':20}
key_common(dict_1, dict_2)

Output

A is identified as the common key
S is identified as the common key
E is identified as the common key

Using items() function

The program uses items() which returns the view object of the dictionary by including a key with value pair. To check the common matches it will return unique keys from the dictionary by using built−in method keys().

Example

In the following example, we will first create the two variables− dict_1 and dict_2 that will declare the two dictionaries consisting of key and value. For the view object of dictionary, it will use the built−in function items() in both the variable by using the operator ‘&’ and store it in the variable result. Next, it will use dictionary comprehension where variable i loop through each item of the result and store it in the variable res. Using the operator ‘&’ it checks both the keys by using built−in function keys() and stores it in the variable common_keys. Finally, print the result with the help of variable common_keys.

dict_1 = {"a": 1, "b":2, "c":3, "d":4}
dict_2 = {"t1": 1, "b":2, "e":5, "c":3}
# view object of common keys
result = dict_1.items() & dict_2.items() 
# In dictionary format
res = {i[0]:i[1] for i in result}  # i[0]:i[1] means each item in the list result.
common_keys = dict_1.keys() & dict_2.keys()  
print("Common Key:", common_keys)

Output

Common Key: {'b', 'c'}

Using set() function in for loop

The set() function is used to convert the dictionary items into a set of tuples. Then the operator ‘&’ is used to perform a set intersection to find the common match of the key.

Example

In the following example, the program compares two dictionaries (dict_1 and dict_2) and prints the key−value pairs that are present in both dictionaries. Then the for loop iterates over the resulting set of tuples and the print() function is used to display the key-value pairs that are present in both dictionaries.

dict_1 = {"a": 1, "b": 2, "c": 3, "d": 4}
dict_2 = {"t1": 1, "b": 2, "e": 5, "c": 3}

for (key, value) in set(dict_1.items()) & set(dict_2.items()):
    print('%s: %s is present in both dict_1 and dict_2' % (key, value))

Output

b: 2 is present in both dict_1 and dict_2
c: 3 is present in both dict_1 and dict_2

Using intersection() method

The program uses the built-in function that compares the two dictionary to find the common key.

Example

In the following example, start creating two dictionaries that store the key along with values. Then using built-in functions set() and intersection() will find the common match from the variables a and b. This process is stored in the variable k_common. Next, using the for loop it will iterate through k_common to sort the common key from the dictionary. The built-in function sorted() is defined by the shortening of the key. Moving ahead to use the print function set the parameters- key and end to get the desired result.

a = {"ab": 11, "bc": 21, "cd": 13, "de": 41}
b = {"cd": 33, "ad": 14, "de": 51, "fa": 16}
k_common = set(a).intersection(b)
print("Common Key from two dictionaries:")
for key in sorted(k_common):
	print(key, end=" ")

Output

Common Key from two dictionaries:
cd de 

Using filter() and lambda

The program uses filter() to remove the those unique keys that are not found to be common key and lambda to calculate the common key from the dictionary.

Example

In the following example, we will start the program by creating two variables i.e. a and b. Then use the built-in functions like filter() in the variable c_keys which will find the common match of key from the both dictionary. Next, using for loop the key iterates through built-in function sorted that accepts parameter named c_keys to generate the common key. Then print the result by using parameters key and end.

a = {"abc": 11, "bax": 21, "cxs": 37, "qwd": 44}
b = {"ccc": 30, "qwd": 41, "bax": 75, "esf": 67}
c_keys = filter(lambda x: x in a, b)
print("Common Keys from two dictionary:\n")
for key in sorted(c_keys):
	print(key, end=" ")

Output

Common Keys from the dictionary:

bax qwd 

Conclusion

We discussed the various methods to solve this problem statement. Then learned the different built-in functions of Python like set(), intersection(), filter(), etc. to get the common key from the dictionary. This type of program helps to build the logic based on a searching algorithm.

Updated on: 14-Aug-2023

245 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements