How to Common keys in list and dictionary using Python


In this article, we will learn how to find common keys in a list and dictionary in python.

Methods Used

The following are the various methods to accomplish this task −

  • Using the ‘in’ operator and List Comprehension

  • Using set(), intersection() functions

  • Using keys() function & in operator

  • Using the Counter() function

Example

Assume we have taken an input dictionary and list. We will find the common elements in the input list and keys of a dictionary using the above methods.

Input

inputDict = {"hello": 2, "all": 4, "welcome": 6, "to": 8, "tutorialspoint": 10}
inputList = ["hello", "tutorialspoint", "python"]

Output

Resultant list: ['hello', 'tutorialspoint']

In the above example, 'hello' and 'tutorialspoint' are the common elements in the input list and keys of a dictionary. Hence they are printed.

Method 1: Using the ‘in’ operator and List Comprehension

List Comprehension

When you wish to build a new list based on the values of an existing list, list comprehension provides a shorter/concise syntax.

Python ‘in’ keyword

The in keyword works in two ways −

  • The in keyword is used to determine whether a value exists in a sequence (list, range, string, etc).

  • It is also used to iterate through a sequence in a for loop

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task –.

  • Create a variable to store the input dictionary.

  • Create another variable to store the input list.

  • Traverse through the input list and check whether any input list element matches the keys of a dictionary using list comprehension.

  • Print the resultant list.

Example

The following program returns common elements in the input list and dictionary keys using the ‘in’ operator and list comprehension –

# input dictionary
inputDict = {"hello": 2, "all": 4, "welcome": 6, "to": 8, "tutorialspoint": 10}

# printing input dictionary
print("Input dictionary:", inputDict)

# input list
inputList = ["hello", "tutorialspoint", "python"]

# printing input list
print("Input list:", inputList)

# checking whether any input list element matches the keys of a dictionary
outputList = [e for e in inputDict if e in inputList]

# printing the resultant list
print("Resultant list:", outputList)

Output

On executing, the above program will generate the following output –

Input dictionary: {'hello': 2, 'all': 4, 'welcome': 6, 'to': 8, 'tutorialspoint': 10}
Input list: ['hello', 'tutorialspoint', 'python']
Resultant list: ['hello', 'tutorialspoint']

Method 2: Using set(), intersection() functions

set() function − creates a set object. A set list will appear in random order because the items are not ordered. It removes all the duplicates.

intersection() function − A set containing the similarity between two or more sets is what the intersection() method returns.

It means Only items that are present in both sets, or in all sets if more than two sets are being compared, are included in the returned set.

Example

The following program returns common elements in the input list and dictionary keys using set() and intersection() –

# input dictionary
inputDict = {"hello": 2, "all": 4, "welcome": 6, "to": 8, "tutorialspoint": 10}

# printing input dictionary
print("Input dictionary:", inputDict)

# input list
inputList = ["hello", "tutorialspoint", "python"]

# printing input list
print("Input list:", inputList)

# Converting the input dictionary and input List to sets

# getting common elements in input list and input dictionary keys

# from these two sets using the intersection() function
outputList = set(inputList).intersection(set(inputDict))

# printing the resultant list
print("Resultant list:", outputList)

Output

On executing, the above program will generate the following output –

Input dictionary: {'hello': 2, 'all': 4, 'welcome': 6, 'to': 8, 'tutorialspoint': 10}
Input list: ['hello', 'tutorialspoint', 'python']
Resultant list: {'hello', 'tutorialspoint'}

Method 3: Using keys() function & in operator

keys() function − the dict. keys() method provides a view object that displays a list of all the keys in the dictionary in order of insertion.

Example

The following program returns common elements in the input list and dictionary keys using the keys() function and in operator–

# input dictionary
inputDict = {"hello": 2, "all": 4, "welcome": 6, "to": 8, "tutorialspoint": 10}

# printing input dictionary
print("Input dictionary:", inputDict)

# input list
inputList = ["hello", "tutorialspoint", "python"]

# printing input list
print("Input list:", inputList)

# empty list for storing the common elements in the list and dictionary keys
outputList = []

# getting the list of keys of a dictionary
keysList = list(inputDict.keys())

# traversing through the keys list
for k in keysList:
   
   # checking whether the current key is present in the input list
   if k in inputList:
      
      # appending that key to the output list
      outputList.append(k)
      
# printing the resultant list
print("Resultant list:", outputList)

Output

Input dictionary: {'hello': 2, 'all': 4, 'welcome': 6, 'to': 8, 'tutorialspoint': 10}
Input list: ['hello', 'tutorialspoint', 'python']
Resultant list: ['hello', 'tutorialspoint']

Method 4: Using the Counter() function

Counter() function − a sub-class that counts the hashable objects. It implicitly creates a hash table of an iterable when called/invoked.

Here the Counter() function is used to get the frequency of input list elements.

Example

The following program returns common elements in the input list and dictionary keys using the Counter() function –

# importing a Counter function from the collections module
from collections import Counter

# input dictionary
inputDict = {"hello": 2, "all": 4, "welcome": 6, "to": 8, "tutorialspoint": 10}

# printing input dictionary
print("Input dictionary:", inputDict)

# input list
inputList = ["hello", "tutorialspoint", "python"]

# printing input list
print("Input list:", inputList)

# getting the frequency of input list elements as a dictionary
frequency = Counter(inputList)

# empty list for storing the common elements of the list and dictionary keys
outputList = []

# getting the list of keys of a dictionary
keysList = list(inputDict.keys())

# traversing through the keys list
for k in keysList:

   # checking whether the current key is present in the input list
   if k in frequency.keys():
      
      # appending/adding that key to the output list
      outputList.append(k)
      
# printing the resultant list
print("Resultant list:", outputList)

Output

Input dictionary: {'hello': 2, 'all': 4, 'welcome': 6, 'to': 8, 'tutorialspoint': 10}
Input list: ['hello', 'tutorialspoint', 'python']
Resultant list: ['hello', 'tutorialspoint']

Conclusion

We studied four different methods in this article for displaying the Common keys in the given list and dictionary. We also learned how to get a dictionary of the iterables' frequencies using the Counter() function.

Updated on: 27-Jan-2023

651 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements