Python - Extract Maximum Keys' value dictionaries
Last Updated :
12 Apr, 2023
Given a dictionary, extract all the dictionary which contains a any key which has maximum values among other keys in dictionary list.
Input : [{"Gfg" : 3, "is" : 7, "Best" : 8}, {"Gfg" : 9, "is" : 2, "Best" : 9}, {"Gfg" : 5, "is" : 4, "Best" : 10}, {"Gfg" : 3, "is" : 6, "Best" : 14}]
Output : [{"Gfg" : 3, "is" : 7, "Best" : 8}, {"Gfg" : 9, "is" : 2, "Best" : 9}, {"Gfg" : 3, "is" : 6, "Best" : 14}]
Explanation : "Gfg" has 9 as best, "is" has 7 and "Best" has 14, those dictionaries are extracted.
Input : [{"Gfg" : 3, "is" : 7, "Best" : 8}, {"Gfg" : 9, "is" : 2, "Best" : 9}, {"Gfg" : 5, "is" : 4, "Best" : 10}, {"Gfg" : 3, "is" : 6, "Best" : 16}]
Output : [{"Gfg" : 3, "is" : 7, "Best" : 8}, {"Gfg" : 9, "is" : 2, "Best" : 9}, {"Gfg" : 3, "is" : 6, "Best" : 16}]
Explanation : "Gfg" has 9 as best, "is" has 7 and "Best" has 16, those dictionaries are extracted.
Method : Using max() + filter() + lambda
The combination of the above functionalities can be used to solve this problem. In this, first maximum is extracted for a particular key and then all dictionaries matching the maximum key are extracted. This is carried out for all the keys.
Python3
# Python3 code to demonstrate working of
# Extract Maximum Keys' value dictionaries
# Using max() + filter() + lambda
# initializing list
test_list = [{"Gfg": 3, "is": 7, "Best": 8},
{"Gfg": 9, "is": 2, "Best": 9},
{"Gfg": 5, "is": 4, "Best": 10},
{"Gfg": 3, "is": 6, "Best": 8}]
# printing original list
print("The original list : " + str(test_list))
res = []
# getting all keys
all_keys = list(test_list[0].keys())
for sub in all_keys:
# extracting maximum of each keys
temp = max(test_list, key=lambda ele: ele[sub])
res_key = list(filter(lambda ele: ele[sub] == temp[sub], test_list))
res.append(res_key)
# printing result
print("The extracted maximum key values dictionaries : " + str(res))
OutputThe original list : [{'Gfg': 3, 'is': 7, 'Best': 8}, {'Gfg': 9, 'is': 2, 'Best': 9}, {'Gfg': 5, 'is': 4, 'Best': 10}, {'Gfg': 3, 'is': 6, 'Best': 8}]
The extracted maximum key values dictionaries : [[{'Gfg': 9, 'is': 2, 'Best': 9}], [{'Gfg': 3, 'is': 7, 'Best': 8}], [{'Gfg': 5, 'is': 4, 'Best': 10}]]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 2: Using a for loop to iterate through each dictionary and comparing the values of each key with the maximum value of that key found so far.
Approach:
- Initialize an empty dictionary max_dict to keep track of the maximum values for each key.
- Iterate through each dictionary in test_list.
- For each dictionary, iterate through each key-value pair using a for loop.
- For each key-value pair, check if the key is already in max_dict. If not, add the key to max_dict and set its value to the value of the current key-value pair.
- If the key is already in max_dict, compare the value of the current key-value pair with the value in max_dict for that key. If the current value is greater, update the value in max_dict for that key.
- Once all dictionaries have been processed, initialize an empty list res.
- Iterate through each dictionary in test_list again.
- For each dictionary, create an empty dictionary temp_dict.
- Iterate through each key-value pair using a for loop.
- For each key-value pair, check if the value for that key in the current dictionary is equal to the maximum value for that key found in max_dict. If it is, add the key-value pair to temp_dict.
- Append temp_dict to res.
- Print the result.
Example:
Python3
test_list = [{"Gfg": 3, "is": 7, "Best": 8},
{"Gfg": 9, "is": 2, "Best": 9},
{"Gfg": 5, "is": 4, "Best": 10},
{"Gfg": 3, "is": 6, "Best": 8}]
# Step 1
max_dict = {}
# Step 2
for d in test_list:
# Step 3
for k, v in d.items():
# Step 4
if k not in max_dict:
max_dict[k] = v
# Step 5
elif v > max_dict[k]:
max_dict[k] = v
# Step 6
res = []
# Step 7
for k in max_dict:
# Step 8
temp_dict = {}
# Step 9
for d in test_list:
# Step 10
if d[k] == max_dict[k]:
temp_dict[k] = d[k]
# Step 11
res.append(temp_dict)
# Step 12
print("The extracted maximum key values dictionaries : " + str(res))
OutputThe extracted maximum key values dictionaries : [{'Gfg': 9}, {'is': 7}, {'Best': 10}]
Time complexity: O(nk), where n is the number of dictionaries in test_list and k is the average number of keys in each dictionary.
Auxiliary space: O(k), where k is the average number of keys in each dictionary.
Method 3 :Using a dictionary comprehension
Steps:
Initialize the input list of dictionaries.
Print the original list.
Get all the keys of the dictionaries in the list.
Use dictionary comprehension to iterate over the keys and extract the maximum value for each key using the max() function and lambda function as the key argument to compare based on the current key.
The output is a list of dictionaries with only one key-value pair that corresponds to the maximum value for each key.
Print the extracted maximum key values dictionaries.
Python3
# Python3 code to demonstrate working of
# Extract Maximum Keys' value dictionaries
# Using dictionary comprehension
# initializing list
test_list = [{"Gfg": 3, "is": 7, "Best": 8},
{"Gfg": 9, "is": 2, "Best": 9},
{"Gfg": 5, "is": 4, "Best": 10},
{"Gfg": 3, "is": 6, "Best": 8}]
# printing original list
print("The original list : " + str(test_list))
# getting all keys
all_keys = list(test_list[0].keys())
# using dictionary comprehension to extract maximum value for each key
res = [{k: max(test_list, key=lambda x: x[k])[k]} for k in all_keys]
# printing result
print("The extracted maximum key values dictionaries : " + str(res))
OutputThe original list : [{'Gfg': 3, 'is': 7, 'Best': 8}, {'Gfg': 9, 'is': 2, 'Best': 9}, {'Gfg': 5, 'is': 4, 'Best': 10}, {'Gfg': 3, 'is': 6, 'Best': 8}]
The extracted maximum key values dictionaries : [{'Gfg': 9}, {'is': 7}, {'Best': 10}]
The time complexity of this approach is O(n*k), where n is the number of dictionaries in the input list and k is the number of keys in each dictionary.
The auxiliary space is O(k), as we only store the keys and the output dictionaries with one key-value pair.
Similar Reads
Python - Extract Key's value from Mixed Dictionaries List
Given a list of dictionaries, with each dictionary having different keys, extract value of key K. Input : test_list = [{"Gfg" : 3, "b" : 7}, {"is" : 5, 'a' : 10}, {"Best" : 9, 'c' : 11}], K = 'b' Output : 7 Explanation : Value of b is 7. Input : test_list = [{"Gfg" : 3, "b" : 7}, {"is" : 5, 'a' : 10
7 min read
Minimum Value Keys in Dictionary - Python
We are given a dictionary and need to find all the keys that have the minimum value among all key-value pairs. The goal is to identify the smallest value in the dictionary and then collect every key that matches it. For example, in {'a': 3, 'b': 1, 'c': 2, 'd': 1}, the minimum value is 1, so the res
4 min read
Python - Extract ith Key's Value of K's Maximum value dictionary
Given Dictionary List, extract i'th keys value depending upon Kth key's maximum value. Input : test_list = [{"Gfg" : 3, "is" : 9, "best" : 10}, {"Gfg" : 8, "is" : 11, "best" : 19}, {"Gfg" : 9, "is" : 16, "best" : 1}], K = "best", i = "is" Output : 11 Explanation : best is max at 19, its correspondin
9 min read
Python - Maximum record value key in dictionary
Sometimes, while working with dictionary records, we can have a problem in which we need to find the key with maximum value of a particular key of nested records in list. This can have applications in domains such as web development and Machine Learning. Lets discuss certain ways in which this task
6 min read
Python Iterate Dictionary Key, Value
In Python, a Dictionary is a data structure that stores the data in the form of key-value pairs. It is a mutable (which means once created we modify or update its value later on) and unordered data structure in Python. There is a thing to keep in mind while creating a dictionary every key in the dic
3 min read
Python - Extract Numerical Dictionary values
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to extract only if a particular key index is numeric value from the dictionaries which are in form of strings. This can be desired in applications in which we require to do preprocessing. Let's discuss certain
5 min read
Get Maximum of Each Key Dictionary List - Python
We are given a list of dictionaries and our task is to find the maximum value for each key across all dictionaries. If a key appears in multiple dictionaries we take the highest value among them. For example: a = [{'a': 3, 'b': 8}, {'a': 10, 'b': 2, 'c': 5}, {'c': 12, 'a': 7}] then the output will b
2 min read
Python - Maximum available value Dictionaries
Given list of dictionaries and a list, extract all the dictionaries which contain maximum available value of key from list. Input : test_list [{"Gfg" : 6, "is" : 9, "best" : 10}, {"Gfg" : 8, "is" : 11, "best" : 19}, {"Gfg" : 2, "is" : 16, "best" : 10}], K = "best", arg_list = [10, 7, 6, 12] Output :
4 min read
Python | Extract filtered Dictionary Values
While working with Python dictionaries, there can be cases in which we are just concerned about getting the filtered values list and donât care about keys. This is yet another essential utility and solution to it should be known and discussed. Letâs perform this task through certain methods. Method
4 min read
Python program to extract N largest dictionaries keys
Given a dictionary, extract the largest N dictionaries keys in descending order. Input : test_dict = {6 : 2, 8: 9, 3: 9, 10: 8}, N = 3 Output : [10, 8, 6] Explanation : Max. N keys extracted in descending order.Input : test_dict = {6 : 2, 8: 9, 3: 9, 10: 8}, N = 2 Output : [10, 8] Explanation : Max.
5 min read