![]() |
VOOZH | about |
Sometimes, while working with dictionaries, we can have a problem in which we need to keep the dictionaries which are having similar key's value in other dictionary. This is a very specific problem. This can have applications in web development domain. Lets discuss certain ways in which this task can be performed. Method #1 : Using list comprehension This task can be performed using list comprehension. In this we iterate each element in list and nesting loop is run to match key's value with every other value.
The original list is : [{'is': 2, 'Gfg': 1}, {'is': 2, 'Gfg': 2}, {'is': 2, 'Gfg': 1}]
List after keeping dictionary with same key's value : [{'is': 2, 'Gfg': 1}, {'is': 2, 'Gfg': 1}]Time Complexity: O(n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n) where n is the number of elements in the list “test_list”.
Method #2 : Using Counter() + list comprehension In this method, the task of finding the frequency is performed using Counter() and then task of finding the elements having multiple keys value is done using list comprehension.
The original list is : [{'is': 2, 'Gfg': 1}, {'is': 2, 'Gfg': 2}, {'is': 2, 'Gfg': 1}]
List after keeping dictionary with same key's value : [{'is': 2, 'Gfg': 1}, {'is': 2, 'Gfg': 1}]Method 3 : use a nested loop
step-by-step approach:
Initialize an empty list result to store the dictionaries that have multiple similar values.
Loop through the list of dictionaries using a for loop and enumerate function to access the index of each dictionary.
For each dictionary, create a list values that contains the values of the dictionary.
Use another for loop to iterate through the remaining dictionaries in the list and compare their values with the values list.
If the values of the two dictionaries are the same, append both dictionaries to the result list.
Return the result list.
The original list is : [{'Gfg': 1, 'is': 2}, {'Gfg': 2, 'is': 2}, {'Gfg': 1, 'is': 2}]
List after keeping dictionary with same key's value : [{'Gfg': 1, 'is': 2}, {'Gfg': 1, 'is': 2}]
Time complexity: O(n^2), where n is the length of the input list.
Auxiliary space: O(k), where k is the number of dictionaries with multiple similar values.