Friday, December 27, 2024
Google search engine
HomeLanguagesPython Program to display keys with same values in a dictionary List

Python Program to display keys with same values in a dictionary List

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.

Python3




# initializing Matrix
test_list = [{"Gfg": 5, "is": 8, "best": 0},
             {"Gfg": 5, "is": 1, "best": 0},
             {"Gfg": 5, "is": 0, "best": 0}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# getting keys
keys = list(test_list[0].keys())
 
res = []
# iterating each dictionary for similar key's value
for key in keys:
    flag = 1
    for ele in test_list:
 
        # checking for similar values
        if test_list[0][key] != ele[key]:
            flag = 0
            break
 
    if flag:
        res.append(key)
 
# printing result
print("Similar values keys : " + str(res))


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.

Python3




# initializing Matrix
test_list = [{"Gfg": 5, "is": 8, "best": 0},
             {"Gfg": 5, "is": 1, "best": 0},
             {"Gfg": 5, "is": 0, "best": 0}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# getting keys
keys = list(test_list[0].keys())
 
res = []
 
# iterating each dictionary for similar key's value
for key in keys:
 
    # using all to check all keys with similar values
    flag = all(test_list[0][key] == ele[key] for ele in test_list)
 
    if flag:
        res.append(key)
 
# printing result
print("Similar values keys : " + str(res))


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:

  • Initialize an empty set intersection_set to store the keys with similar values.
  • Iterate through the keys of the first dictionary in the test_list using a for loop.
  • For each key, check if the values of that key in all the dictionaries in the test_list are the same using a list comprehension and the set() function.
  • If the length of the resulting set is 1, then add the key to the intersection_set.
  • Print the intersection_set.

Below is the implementation of the above approach:

Python3




# initializing Matrix
test_list = [{"Gfg": 5, "is": 8, "best": 0},
             {"Gfg": 5, "is": 1, "best": 0},
             {"Gfg": 5, "is": 0, "best": 0}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# getting keys of first dictionary
keys = test_list[0].keys()
 
# initializing set to store keys with similar values
intersection_set = set()
 
# iterating each key of first dictionary
for key in keys:
     
    # getting values of key from all dictionaries in the list
    values = set(d[key] for d in test_list)
     
    # checking if all values of the key are the same
    if len(values) == 1:
        intersection_set.add(key)
 
# printing result
print("Similar values keys : " + str(list(intersection_set)))


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*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:

  1. Import the reduce function from functools module
  2. Initialize the test_list with dictionaries containing key-value pairs
  3. Get the keys of the first dictionary from the test_list
  4. Use the reduce function to iterate over the keys and check if all the values in the corresponding key in all the dictionaries are equal to the value of that key in the first dictionary. If yes, add the key to the result list.
  5. Print the result list.

Python3




from functools import reduce
 
# initializing Matrix
test_list = [{"Gfg": 5, "is": 8, "best": 0},
            {"Gfg": 5, "is": 1, "best": 0},
            {"Gfg": 5, "is": 0, "best": 0}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# getting keys
keys = list(test_list[0].keys())
 
# using reduce to check all keys with similar values
res = reduce(lambda acc, key: acc + ([key] if all(test_list[0][key] == ele[key] for ele in test_list) else []), keys, [])
 
# printing result
print("Similar values keys : " + str(res))
#This code is contributed by Vinay pinjala


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*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.

RELATED ARTICLES

Most Popular

Recent Comments