Python Program to display keys with same values in a dictionary List
Last Updated :
21 Apr, 2023
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
test_list = [{ "Gfg" : 5 , "is" : 8 , "best" : 0 },
{ "Gfg" : 5 , "is" : 1 , "best" : 0 },
{ "Gfg" : 5 , "is" : 0 , "best" : 0 }]
print ( "The original list is : " + str (test_list))
keys = list (test_list[ 0 ].keys())
res = []
for key in keys:
flag = 1
for ele in test_list:
if test_list[ 0 ][key] ! = ele[key]:
flag = 0
break
if flag:
res.append(key)
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
test_list = [{ "Gfg" : 5 , "is" : 8 , "best" : 0 },
{ "Gfg" : 5 , "is" : 1 , "best" : 0 },
{ "Gfg" : 5 , "is" : 0 , "best" : 0 }]
print ( "The original list is : " + str (test_list))
keys = list (test_list[ 0 ].keys())
res = []
for key in keys:
flag = all (test_list[ 0 ][key] = = ele[key] for ele in test_list)
if flag:
res.append(key)
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
test_list = [{ "Gfg" : 5 , "is" : 8 , "best" : 0 },
{ "Gfg" : 5 , "is" : 1 , "best" : 0 },
{ "Gfg" : 5 , "is" : 0 , "best" : 0 }]
print ( "The original list is : " + str (test_list))
keys = test_list[ 0 ].keys()
intersection_set = set ()
for key in keys:
values = set (d[key] for d in test_list)
if len (values) = = 1 :
intersection_set.add(key)
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:
- Import the reduce function from functools module
- Initialize the test_list with dictionaries containing key-value pairs
- Get the keys of the first dictionary from the test_list
- 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.
- Print the result list.
Python3
from functools import reduce
test_list = [{ "Gfg" : 5 , "is" : 8 , "best" : 0 },
{ "Gfg" : 5 , "is" : 1 , "best" : 0 },
{ "Gfg" : 5 , "is" : 0 , "best" : 0 }]
print ( "The original list is : " + str (test_list))
keys = list (test_list[ 0 ].keys())
res = reduce ( lambda acc, key: acc + ([key] if all (test_list[ 0 ][key] = = ele[key] for ele in test_list) else []), keys, [])
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*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.
Similar Reads
Python program to group keys with similar values in a dictionary
Given a dictionary with values as a list. Group all the keys together with similar values. Input : test_dict = {"Gfg": [5, 6], "is": [8, 6, 9], "best": [10, 9], "for": [5, 2], "geeks": [19]} Output : [['Gfg', 'is', 'for'], ['is', 'Gfg', 'best'], ['best', 'is'], ['for', 'Gfg']] Explanation : Gfg has
2 min read
Python program to Swap Keys and Values in Dictionary
Dictionary is quite a useful data structure in programming that is usually used to hash a particular key with value so that they can be retrieved efficiently. Letâs discuss various ways of swapping the keys and values in Python Dictionary. Method#1 (Does not work when there are multiple same values)
4 min read
Python program that renders a dictionary from two list with K values
Given two list, one will be used to provide keys to dictionary and the other for values. The following program takes K values from second list and assigns it to each key, creating a dictionary of the following kind: Input : test_list = ["gfg", "best"], val_list = [1, 4, 5, 6, 7, 8, 8, 5], K = 4 Outp
5 min read
Python | Sum list of dictionaries with same key
You have given a list of dictionaries, the task is to return a single dictionary with sum values with the same key. Let's discuss different methods to do the task. Method #1: Using reduce() + operator Step-by-step approach: Import necessary modules - collections, functools, and operator.Initialize a
7 min read
Filter Dictionary Key based on the Values in Selective List - Python
We are given a dictionary where each key is associated with a value and our task is to filter the dictionary based on a selective list of values. We want to retain only those key-value pairs where the value is present in the list. For example, we have the following dictionary and list: d = {'apple':
3 min read
Python program to check whether the values of a dictionary are in same order as in a list
Given a dictionary, test if values are in order with list values. Input : test_dict = {"gfg" : 4, "is" : 10, "best" : 11}, sub_list = [4, 10, 11] Output : True Explanation : Values are 4, 10, 11, same as list order. Hence True is returned. Input : test_dict = {"gfg" : 4, "is" : 10, "best" : 11}, sub
6 min read
Python | Find keys with duplicate values in dictionary
Given a dictionary, the task is to find keys with duplicate values. Let's discuss a few methods for the same. Method #1: Using Naive approach In this method first, we convert dictionary values to keys with the inverse mapping and then find the duplicate keys C/C++ Code # Python code to demonstrate #
4 min read
Python | Segregating key's value in list of dictionaries
While working with dictionaries, we may encounter problems in which we need to segregate all the similar keys' values together. This kind of problem can occur in web development domain while working with databases. Let's discuss certain ways in which this problem can be solved. Method #1: Using gene
6 min read
Search for Value in the Python Dictionary with Multiple Values for a Key
In Python, searching for a value in a dictionary with multiple values for a key involves navigating through key-value pairs efficiently. This scenario often arises when a key maps to a list, tuple, or other iterable as its value. In this article, we will explore four different approaches to searchin
4 min read
Python - Group Similar items to Dictionary Values List
We are given a list of items and our task is to group similar elements together as dictionary values. The keys will be the unique items and their values will be lists containing all occurrences of that item. For example, given ['apple', 'banana', 'apple', 'orange', 'banana'], the output should be: {
2 min read