![]() |
VOOZH | about |
Given two dictionary lists, remove all the dictionaries which have similar value of K key from other dictionary list.
Input : test_list = [{'Gfg' : 3, "is" : 3, "best" : 9},
{'Gfg' : 8, "is" : 4, "best" : 2},
{'Gfg' : 9, "is" : 2, "best" : 4},
{'Gfg' : 8, "is" : 10, "best" : 3},
{'Gfg' : 7, "is" : 1, "best" : 7}], check_list = [{'Gfg' : 8, "Best" : 1}, {"Best" : 2, "Gfg" : 7}], K = "Gfg"
Output : [{'Gfg': 3, 'is': 3, 'best': 9}, {'Gfg': 9, 'is': 10, 'best': 3}]
Explanation : All dictionaries with "Gfg"'s value as 8 or 7 is removed.
Input : test_list = [{'Gfg' : 3, "is" : 3, "best" : 9},
{'Gfg' : 8, "is" : 4, "best" : 2}], check_list = [{'Gfg' : 8, "Best" : 1}, {"Best" : 2, "Gfg" : 7}], K = "Gfg"
Output : [{'Gfg': 3, 'is': 3, 'best': 9}]
Explanation : All dictionaries with "Gfg"'s value as 8 or 7 is removed.
Method 1: Using list comprehension + dictionary comprehension
In this, we perform tasks of getting a set of elements using dictionary comprehension, and then a new list is constructed using list comprehension by testing K key's values absence in the constructed set of values.
The whole task is conducted in two steps,
Output:
The original list is : [{'Gfg': 3, 'is': 3, 'best': 9}, {'Gfg': 8, 'is': 4, 'best': 2}, {'Gfg': 1, 'is': 2, 'best': 4}, {'Gfg': 9, 'is': 10, 'best': 3}, {'Gfg': 7, 'is': 1, 'best': 7}] Dictionary list after removal : [{'Gfg': 3, 'is': 3, 'best': 9}, {'Gfg': 1, 'is': 2, 'best': 4}, {'Gfg': 9, 'is': 10, 'best': 3}]
Time Complexity: O(n)
Auxiliary Space: O(1)
Method 2 : Using filter() function and lambda function
Dictionary list after removal : [{'Gfg': 3, 'is': 3, 'best': 9}, {'Gfg': 1, 'is': 2, 'best': 4}, {'Gfg': 9, 'is': 10, 'best': 3}]Time complexity: O(n), where n is the number of dictionaries in the original list, test_list.
Auxiliary space: O(m), where m is the number of dictionaries in the check_list.
Method 3: Using a for loop and a new list to store the desired output.
Here are the steps:
Dictionary list after removal : [{'Gfg': 3, 'is': 3, 'best': 9}, {'Gfg': 1, 'is': 2, 'best': 4}, {'Gfg': 9, 'is': 10, 'best': 3}]The time complexity of this method is O(n*m), where n is the length of test_list and m is the length of check_list.
The auxiliary space complexity is O(k), where k is the length of result_list.