Python - Compare Dictionaries on certain Keys
Last Updated :
21 Apr, 2023
Sometimes, while working with Python dictionaries, we can have a problem in which we need to compare dictionaries for equality on bases in selected keys. This kind of problem is common and has application in many domains. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loop This is brute force way in which this task can be performed. In this, we iterate for both the dictionary and manually test for keys equality using equality operator from selected keys.
Python3
# Python3 code to demonstrate working of
# Compare Dictionaries on certain Keys
# Using loop
# initializing dictionaries
test_dict1 = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 4, 'geeks' : 5}
test_dict2 = {'gfg' : 2, 'is' : 3, 'best' : 3, 'for' : 7, 'geeks' : 5}
# printing original dictionaries
print("The original dictionary 1 : " + str(test_dict1))
print("The original dictionary 2 : " + str(test_dict2))
# initializing compare keys
comp_keys = ['best', 'geeks']
# Compare Dictionaries on certain Keys
# Using loop
res = True
for key in comp_keys:
if test_dict1.get(key) != test_dict2.get(key):
res = False
break
# printing result
print("Are dictionary equal : " + str(res))
Output :
The original dictionary 1 : {'geeks': 5, 'gfg': 1, 'is': 2, 'for': 4, 'best': 3} The original dictionary 2 : {'geeks': 5, 'gfg': 2, 'is': 3, 'for': 7, 'best': 3} Are dictionary equal : True
Method #2 : Using all() This is one liner alternative to perform this task. In this the functionality of comparison is done using all(), comparing all required keys.
Python3
# Python3 code to demonstrate working of
# Compare Dictionaries on certain Keys
# Using all()
# initializing dictionaries
test_dict1 = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 4, 'geeks' : 5}
test_dict2 = {'gfg' : 2, 'is' : 3, 'best' : 3, 'for' : 7, 'geeks' : 5}
# printing original dictionaries
print("The original dictionary 1 : " + str(test_dict1))
print("The original dictionary 2 : " + str(test_dict2))
# initializing compare keys
comp_keys = ['best', 'geeks']
# Compare Dictionaries on certain Keys
# Using all()
res = all(test_dict1.get(key) == test_dict2.get(key) for key in comp_keys)
# printing result
print("Are dictionary equal : " + str(res))
Output :
The original dictionary 1 : {'geeks': 5, 'gfg': 1, 'is': 2, 'for': 4, 'best': 3} The original dictionary 2 : {'geeks': 5, 'gfg': 2, 'is': 3, 'for': 7, 'best': 3} Are dictionary equal : True
Method #3 : Using Dictionary comprehension and all() function
Approach
we use dictionary comprehension to create a new dictionary with only the common keys in both dictionaries. Then, we use all() function to compare the values of the corresponding keys in the two dictionaries.
Algorithm
1. Create a new dictionary using dictionary comprehension with only the common keys in both dictionaries.
2. Use all() function to compare the values of the corresponding keys in the two dictionaries.
3. If the values of all the keys are equal, then the two dictionaries are equal.
Python3
# sample input dictionaries
dict1 = {'geeks': 5, 'gfg': 1, 'is': 2, 'for': 4, 'best': 3}
dict2 = {'geeks': 5, 'gfg': 2, 'is': 3, 'for': 7, 'best': 3}
# create a new dictionary with only common keys in both dictionaries
common_keys = set(dict1.keys()) & set(dict2.keys())
new_dict1 = {key: dict1[key] for key in common_keys}
new_dict2 = {key: dict2[key] for key in common_keys}
# compare values of corresponding keys
if all(new_dict1[key] == new_dict2[key] for key in new_dict1.keys()):
print("Dictionaries are equal")
else:
print("Dictionaries are not equal")
OutputDictionaries are not equal
Time complexity: O(n + k), this code is dependent on a few factors, such as the size of the dictionaries and the number of common keys between them. The first step involves finding the common keys between the two dictionaries, which is an O(n) operation, where n is the length of the largest dictionary. Next, we create two new dictionaries with only the common keys, which also takes O(n) time as we iterate over each key in the set of common keys. we compare the values of corresponding keys, which takes O(k) time, where k is the number of common keys.
Space complexity: O(n+k), this code is also dependent on the size of the dictionaries and the number of common keys. We create two new dictionaries with only the common keys, which would have a space complexity of O(k), where k is the number of common keys. The set of common keys also takes up space, which is O(n), where n is the length of the largest dictionary.
Method 4 : use set operations
Get the common keys in both dictionaries using set intersection operation.
Create two sets, one for values of common keys in dict1 and another for values of common keys in dict2.
Check if both sets are equal.
Python3
# sample input dictionaries
dict1 = {'geeks': 5, 'gfg': 1, 'is': 2, 'for': 4, 'best': 3}
dict2 = {'geeks': 5, 'gfg': 2, 'is': 3, 'for': 7, 'best': 3}
# get common keys in both dictionaries
common_keys = set(dict1.keys()) & set(dict2.keys())
# create sets of values for common keys in both dictionaries
dict1_values = {dict1[key] for key in common_keys}
dict2_values = {dict2[key] for key in common_keys}
# check if both sets of values are equal
if dict1_values == dict2_values:
print("Dictionaries are equal")
else:
print("Dictionaries are not equal")
OutputDictionaries are not equal
Time complexity: O(n), where n is the number of keys in the dictionaries.
Auxiliary space: O(n), to store sets of values for common keys in both dictionaries.
Similar Reads
Combine keys in a list of dictionaries in Python
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform a merge of dictionaries in list with similar keys. This kind of problem can come in data optimization domains. Let's discuss a way in which this task can be performed. Input : test_list = [{'a': 6},
2 min read
How to Compare Two Dictionaries in Python
In this article, we will discuss how to compare two dictionaries in Python. The simplest way to compare two dictionaries for equality is by using the == operator.Using == operatorThis operator checks if both dictionaries have the same keys and values.Pythond1 = {'a': 1, 'b': 2} d2 = {'a': 1, 'b': 2}
2 min read
Python - Common keys in list and dictionary
Given a dictionary and list, extract all the keys and list which are common. Input : test_dict = {"Gfg": 3, "is" : 5, "best" : 9, "for" : 0, "geeks" : 3}, test_list = ["Gfg", "best", "CS"] Output : ['Gfg', 'best'] Explanation : Gfg and best are present in both dictionary and List. Input : test_dict
8 min read
Python - Detect loop in Dictionaries
Sometimes, while working with Python dictionaries, we can have problem in which we need to check if values of dictionaries don't form a loop when they are mapped through key of other dictionaries. This kind of problem can have applications in many domains including competitive programming and brute
4 min read
Python - Add custom values key in List of dictionaries
The task of adding custom values as keys in a list of dictionaries involves inserting a new key-value pair into each dictionary within the list. In Python, dictionaries are mutable, meaning the key-value pairs can be modified or added easily. When working with a list of dictionaries, the goal is to
5 min read
Python - Custom order dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform the custom ordering of keys of dictionary. This is quite popular problem, with the advent of newer version of Python, where keys are ordered in Dictionaries, there might be requirement to reorder dic
3 min read
Convert Nested Tuple to Custom Key Dictionary - Python
The task is to convert a nested tuple into a dictionary with custom keys. Each tuple in the nested structure contains multiple elements, and the goal is to map these elements to specific keys in a dictionary.For example, given the tuple a = ((4, 'Gfg', 10), (3, 'is', 8), (6, 'Best', 10)), the goal i
3 min read
Python - Convert List to List of dictionaries
We are given a lists with key and value pair we need to convert the lists to List of dictionaries. For example we are given two list a=["name", "age", "city"] and b=[["Geeks", 25, "New York"], ["Geeks", 30, "Los Angeles"], ["Geeks", 22, "Chicago"]] we need to convert these keys and values list into
4 min read
Python - Filter Non-None dictionary Keys
Many times, while working with dictionaries, we wish to get keys for a non-null keys. This finds application in Machine Learning in which we have to feed data with no none values. Letâs discuss certain ways in which this task can be performed. Method #1 : Using loop In this we just run a loop for al
6 min read
Python - Convert list of dictionaries to Dictionary Value list
We are given a list of dictionaries we need to convert it to dictionary. For example, given a list of dictionaries: d = [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}, {'a': 5, 'b': 6}], the output should be: {'a': [1, 3, 5], 'b': [2, 4, 6]}.Using Dictionary ComprehensionUsing dictionary comprehension, we can
3 min read