Open In App

Python – Extract Maximum Keys’ value dictionaries

Last Updated : 12 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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))


Output

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

  1. Initialize an empty dictionary max_dict to keep track of the maximum values for each key.
  2. Iterate through each dictionary in test_list.
  3. For each dictionary, iterate through each key-value pair using a for loop.
  4. 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.
  5. 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.
  6. Once all dictionaries have been processed, initialize an empty list res.
  7. Iterate through each dictionary in test_list again.
  8. For each dictionary, create an empty dictionary temp_dict.
  9. Iterate through each key-value pair using a for loop.
  10. 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.
  11. Append temp_dict to res.
  12. 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))


Output

The 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))


Output

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads