Find the common keys from two dictionaries in Python

In this Python tutorial, we will see how to find the common keys from two dictionaries in Python.

A dictionary is a collection of key-value pairs enclosed within curly brackets ‘{ }’. The value can be accessed using the unique key it is assigned to.

For eg: diction={‘Monday’:20,’Tuesday’:30,’Wednesday’:40,’Sunday’:100,’Friday’:80}

Each key is assigned to an index value. In the above example, The dictionary ‘diction’ has the key ‘Monday’  at index ‘0’ with ’20’ as it’s valued, Similarly ‘Tuesday’ has the value ’30’ and is present at index ‘1’ and so on.

The dictionaries in Python have various in-built methods and functions that perform certain operations with respect to the dictionary. Some of them are as follows:

  • diction.clear()– Removes all the elements from the dictionary diction.
  • diction.get(key)– Returns the value against the respective key present inside the dictionary.
  • diction.pop()– Returns the last element of the dictionary and removes it from the dictionary.
  • diction.items()/diction.keys()/diction.values()– Returns the items/keys/values of dictionary diction in a set-like element.
  • diction.__sizeof__()– Returns the size of diction in memory in bytes.
  • diction.copy()– Creates a copy of the dictionary ‘diction’.

Read: Creation, Addition, Removal and Modification of Dictionary in Python

The rest of the methods can be accessed by typing

>>>help(dict)

in the Python IDLE.

Python Code: Find the common keys between two dictionaries

def Common_key(a,b)
      for i in a.keys():
               for j in b.keys(): 
                            if i==j:
                                 print(i "is the common key")
Adict={'Monday':20,'Tuesday':30,'Wednesday':40,'Sunday':100,'Friday':80}
Bdict={'Eggs':200,'Bacon':450,'Sunday':100,'Steak':55,'Monday':20)
Common_key(Adict,Bdict)

OUTPUT:

Sunday is the common key.
Monday is the common key.

Program Explanation:

A user-defined function, “Common key” is used with parameters as the dictionaries ‘a’ and ‘b’ which are to be compared. This program emphasizes the method to compare two dictionaries and find the common keys among the two dictionaries. The ‘a’ and ‘b’ parameters are used within the program as the dictionaries. They are local variables that cannot be used outside the program. This is done by the following steps:

  1. The command ‘a.keys()’ or ‘b.keys()’ creates a list of the keys of the dictionaries ‘a’ and ‘b’ respectively.
  2. These lists’ keys are then traversed respectively as i and j variables.
  3. Then if the keys i and j are equal, they are printed.
  4. In the second code, two dictionaries are allotted to the variables “Adict” and “Bdict”.
  5. The dictionaries “Adict” and “Bdict” are now parameters to the function “Common_Key” while calling it.

Leave a Reply

Your email address will not be published. Required fields are marked *