VOOZH about

URL: https://www.geeksforgeeks.org/python/python-compare-unordered-dictionary-list/

⇱ Python - Compare Unordered Dictionary List - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python - Compare Unordered Dictionary List

Last Updated : 21 Apr, 2023

Sometimes, while working with Records, we can have problem in which we need to perform the comparison between records. This can be of type list of dictionaries, if they are equal or not. This has applications in many domains. Lets discuss certain ways in which this task can be performed. 

Method #1 : Using "==" operator ( Only keys Unordered ) For the case in which just the keys of dictionaries are unordered, and the ordering in list is in correct way, the test can be done using "==" operator. 

Output : 

The original list 1 is : [{'Himani': 15, 'Manjeet': 12}, {'Akshat': 20, 'Vashu': 15}] The original list 2 is : [{'Himani': 15, 'Manjeet': 12}, {'Vashu': 15, 'Akshat': 20}] Are Dictionary Lists equal ? : True

Time complexity: O(1) because it only performs a single operation, which is the comparison of two lists using the == operator.
Auxiliary space: O(1) because it only uses a fixed amount of memory to store the two lists and the result of the comparison. No additional memory is allocated during the execution of the program.

Method #2 : Using sorted() + key + lambda ( In case of Unordered keys and list position ) The combination of above functions can also be used to solve this problem. In this, we perform the task of sorting to resolve the list positioning and then compare. 

Output : 

The original list 1 is : [{'Himani': 15, 'Manjeet': 12}, {'Akshat': 20, 'Vashu': 15}] The original list 2 is : [{'Himani': 15, 'Manjeet': 12}, {'Vashu': 15, 'Akshat': 20}] Are Dictionary Lists equal ? : True

Time complexity: O(nlogn), where n is the number of elements in the test_list.
Auxiliary space: O(n), where n is the number of elements in the test_list. 

Method 3 :  use a combination of set() and frozenset()

we can use a combination of set() and frozenset() to convert each dictionary to a set of frozen sets, where each frozen set is a tuple of key-value pairs. Then, you can compare the two lists of sets using the == operator.


Output
Are Dictionary Lists equal ? : True

 The time complexity of this approach is O(n^2), where n is the number of dictionaries in the lists, and the space complexity is O(n).

Comment