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
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 Convert a list into a dictionary with index as key
We are given a list and our task is to convert it into a dictionary where each elementâs index in the list becomes the key and the element itself becomes the corresponding value. For example, if we have a list like: ['apple', 'banana', 'cherry'] then the output will be {0: 'apple', 1: 'banana', 2: '
2 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 - Convert tuple list to dictionary with key from a given start value
Given a tuple list, the following article focuses on how to convert it to a dictionary, with keys starting from a specified start value. This start value is only to give a head start, next keys will increment the value of their previous keys. Input : test_list = [(4, 5), (1, 3), (9, 4), (8, 2), (10,
4 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 - Value limits to keys in Dictionaries List
Given a Dictionaries list, write a Python program to assign limits to each key in dictionary list.( each having all keys ). Examples: Input : test_list = [{"gfg" : 4, "is" : 7, "best" : 10}, {"gfg" : 2, "is" : 5, "best" : 9}, {"gfg" : 1, "is" : 2, "best" : 6}] Output : {'gfg': [1, 4], 'is': [2, 7],
11 min read
Add a key value pair to Dictionary in Python
The task of adding a key-value pair to a dictionary in Python involves inserting new pairs or updating existing ones. This operation allows us to expand the dictionary by adding new entries or modify the value of an existing key. For example, starting with dictionary d = {'key1': 'geeks', 'key2': 'f
3 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