![]() |
VOOZH | about |
Given a list with all dictionary elements, the task is to write a Python program to extract keys having similar values across all dictionaries.
Examples:
Input : test_list = [{"Gfg": 5, "is" : 8, "best" : 0}, {"Gfg": 5, "is" : 1, "best" : 0}, {"Gfg": 5, "is" : 0, "best" : 0}]
Output : ['Gfg', 'best']
Explanation : All Gfg values are 5 and best has 0 as all its values in all dictionaries.Input : test_list = [{"Gfg": 5, "is" : 8, "best" : 1}, {"Gfg": 5, "is" : 1, "best" : 0}, {"Gfg": 5, "is" : 0, "best" : 0}]
Output : ['Gfg']
Explanation : All Gfg values are 5.
Method 1 : Using keys() and loop
In this, we iterate through all the elements in the list using loop and extract keys using keys(). For each key, each dictionary's key is compared, if found similar, key is added to result.
Output:
The original list is : [{'Gfg': 5, 'is': 8, 'best': 0}, {'Gfg': 5, 'is': 1, 'best': 0}, {'Gfg': 5, 'is': 0, 'best': 0}]
Similar values keys : ['Gfg', 'best']
Time Complexity: O(n*n)
Auxiliary Space: O(n)
Method 2 : Using all(), loop and keys()
In this, inner loop is avoided and replaced by all() which checks for all the keys having similar values and then the key is extracted.
Output:
The original list is : [{'Gfg': 5, 'is': 8, 'best': 0}, {'Gfg': 5, 'is': 1, 'best': 0}, {'Gfg': 5, 'is': 0, 'best': 0}]
Similar values keys : ['Gfg', 'best']
Time Complexity: O(n*n)
Auxiliary Space: O(n)
Method 3: Use the set intersection method.
Step-by-step approach:
Below is the implementation of the above approach:
The original list is : [{'Gfg': 5, 'is': 8, 'best': 0}, {'Gfg': 5, 'is': 1, 'best': 0}, {'Gfg': 5, 'is': 0, 'best': 0}]
Similar values keys : ['Gfg', 'best']Time complexity: O(N*M) where N is the number of dictionaries in the test_list and M is the number of keys in the first dictionary.
Auxiliary space: O(M) to store the intersection_set.
Method 4: Using reduce():
Algorithm:
The original list is : [{'Gfg': 5, 'is': 8, 'best': 0}, {'Gfg': 5, 'is': 1, 'best': 0}, {'Gfg': 5, 'is': 0, 'best': 0}]
Similar values keys : ['Gfg', 'best']
Time Complexity: O(n*m), where n is the number of keys and m is the number of dictionaries in the test_list. This is because we need to iterate over all the keys and dictionaries to check for similar values.
Space Complexity: O(k), where k is the number of keys in the test_list. This is because we are only storing the result list, which can have a maximum of k elements.