Python - Find the Common Keys from two Dictionaries
Last Updated :
13 Feb, 2023
In this article, we will learn how can we print common keys from two Python dictionaries. We will see that there are multiple methods one can do this task. From brute force solutions of nested loops to optimize ones that trade between space and time to decrease the time complexity we will see different methods to do the task at hand and why they work.
Using Nested Loop to get Common Keys from two Dictionaries in Python
We can find Common Keys from two Dictionaries through nested loops. One of the outer loops will be for one dictionary and the other will be for the second dictionary. In this way, we will be able to check for each possible pair of keys. If one of the dictionaries contains m keys and the second one contains n keys then the time complexity and the space complexity of this method will be:
Time Complexity: O(M x N)
Space Complexity: O(1)
Python3
a = {"a": 1, "b": 2, "c": 3, "d": 4}
b = {"c": 3, "d": 4, "e": 5, "f": 6}
for key in a:
if key in b:
print(key, end=" ")
Using & operator to get Common Keys from two Dictionaries in Python
There are some assumptions for this method that is the size of the two dictionaries must be the same and the if the keys are same then the value associated with them must be same as well as this method will not work.
We can find Common Keys from two Dictionaries through & operator. In this method, we will iterate through the values assigned to each of the keys and perform an operation between the items of the two dictionaries. In this way, for the same items, their keys will be the same.
Python3
a = {"a": 1, "b": 2, "c": 3, "d": 4}
b = {"c": 3, "d": 4, "e": 5, "f": 6}
res = a.items() & b.items()
for i in sorted(res):
print(i[0], end=" ")
The time complexity of this program is O(n * log(n)), where n is the total number of items in both dictionaries. This is because the items() method returns a set-like object containing a view of the dictionary's items, and the & operator performs a set intersection operation, both of which have a time complexity of O(n * log(n)). The sorted() function also has a time complexity of O(n * log(n)).
The space complexity is O(n), where n is the total number of items in both dictionaries. This is because the result of the items() method and the set intersection operation is stored in a new set-like object, which requires space proportional to the number of items in both dictionaries.
Using Set's Intersection() to get Common Keys from two Dictionaries in Python
Python set intersection() method returns a new set with an element that is common to all sets. The intersection of two given sets is the largest set, which contains all the elements that are common to both sets.
Python3
a = {"a": 1, "b": 2, "c": 3, "d": 4}
b = {"c": 3, "d": 4, "e": 5, "f": 6}
common_keys = set(a).intersection(b)
for key in sorted(common_keys):
print(key, end=" ")
Time complexity: O(nlogn), where n is the total number of items in both dictionaries.
Auxiliary space: O(n)
Using Dictionary's Get() to get Common Keys from two Dictionaries in Python
Python Dictionary get() Method return the value for the given key if present in the dictionary. If not, then it will return None (if get() is used with only one argument).
Python3
a = {"a": 1, "b": 2, "c": 3, "d": 4}
b = {"c": 3, "d": 4, "e": 5, "f": 6}
for key in a:
name = b.get(key, None)
if name:
print(key, end= " ")
Time complexity: O(n), where n is the total number of items in both dictionaries.
Auxiliary space: O(1)
Filter the keys of dictionary using a lambda function:
To find the common keys between two dictionaries using lambda expressions, we can use the filter() function. The filter() function takes a function and a list as arguments and returns a list containing only the elements for which the function returned True.
Here is an example of how to use filter() to find the common keys between two dictionaries:
Python3
a = {"a": 1, "b": 2, "c": 3, "d": 4}
b = {"c": 3, "d": 4, "e": 5, "f": 6}
common_keys = filter(lambda x: x in a, b)
for key in sorted(common_keys):
print(key, end=" ")
This will print the common keys between the dictionaries a and b, which are c and d.
Time complexity: O(nlogn), where n is the total number of items in both dictionaries.
Auxiliary space: O(n)
Similar Reads
Python | Common items among dictionaries
Sometimes, while working with Python, we can come across a problem in which we need to check for the equal items count among two dictionaries. This has an application in cases of web development and other domains as well. Let's discuss certain ways in which this task can be performed. Method #1 : Us
6 min read
Dictionary with Tuple as Key in Python
Dictionaries allow a wide range of key types, including tuples. Tuples, being immutable, are suitable for use as dictionary keys when storing compound data. For example, we may want to map coordinates (x, y) to a specific value or track unique combinations of values. Let's explores multiple ways to
4 min read
How to Compare List of Dictionaries in Python
Comparing a list of dictionaries in Python involves checking if the dictionaries in the list are equal, either entirely or based on specific key-value pairs. This process helps to identify if two lists of dictionaries are identical or have any differences. The simplest approach to compare two lists
3 min read
Convert Two Lists into a Dictionary - Python
We are given two lists, we need to convert both of the list into dictionary. For example we are given two lists a = ["name", "age", "city"], b = ["Geeks", 30,"Delhi"], we need to convert these two list into a form of dictionary so that the output should be like {'name': 'Geeks', 'age': 30, 'city': '
3 min read
Merging or Concatenating two Dictionaries in Python
Combining two dictionaries is a common task when working with Python, especially when we need to consolidate data from multiple sources or update existing records. For example, we may have one dictionary containing user information and another with additional details and we'd like to merge them into
2 min read
Python | Set 4 (Dictionary, Keywords in Python)
In the previous two articles (Set 2 and Set 3), we discussed the basics of python. In this article, we will learn more about python and feel the power of python. Dictionary in Python In python, the dictionary is similar to hash or maps in other languages. It consists of key-value pairs. The value c
5 min read
Convert nested Python dictionary to object
Let us see how to convert a given nested dictionary into an object Method 1 : Using the json module. We can solve this particular problem by importing the json module and use a custom object hook in the json.loads() method. python3 # importing the module import json # declaringa a class class obj: #
2 min read
Convert Lists to Nested Dictionary - Python
The task of converting lists to a nested dictionary in Python involves mapping elements from multiple lists into key-value pairs, where each key is associated with a nested dictionary. For example, given the lists a = ["gfg", "is", "best"], b = ["ratings", "price", "score"], and c = [5, 6, 7], the g
3 min read
Add new keys to a dictionary in Python
In this article, we will explore various methods to add new keys to a dictionary in Python. Let's explore them with examples:Using Assignment Operator (=)The simplest way to add a new key is by using assignment operator (=).Pythond = {"a": 1, "b": 2} d["c"] = 3 print(d)Output{'a': 1, 'b': 2, 'c': 3}
2 min read
How to Add Duplicate Keys in Dictionary - Python
In Python, dictionaries are used to store key-value pairs. However, dictionaries do not support duplicate keys. In this article, we will explore several techniques to store multiple values for a single dictionary key.Understanding Dictionary Key ConstraintsIn Python, dictionary keys must be unique.
3 min read