Open In App

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 corresponding “is” value is 11. 



Input : test_list = [{“Gfg” : 3, “is” : 9, “best” : 10}, {“Gfg” : 8, “is” : 11, “best” : 19}, {“Gfg” : 9, “is” : 16, “best” : 1}], K = “Gfg”, i = “is” 
Output : 16 
Explanation : Gfg is max at 9, its corresponding “is” value is 16.

Method #1 : Using max() + lambda



The combination of above functions can be used to solve this problem. In this, we extract max of kth key using max() and lambda. Then ith key is extracted from extracted dictionary.




# Python3 code to demonstrate working of
# Extract ith Key's Value of K's Maximum value dictionary
# Using max() + lambda
 
# initializing lists
test_list = [{"Gfg" : 3, "is" : 9, "best" : 10},
             {"Gfg" : 8, "is" : 11, "best" : 19},
             {"Gfg" : 9, "is" : 16, "best" : 1}]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing K
K = "best"
 
# initializing i
i = "Gfg"
 
# using get() to handle missing key, assigning lowest value
res = max(test_list, key = lambda ele : ele.get(K, 0))[i]
     
# printing result
print("The required value : " + str(res))

Output
The original list : [{'Gfg': 3, 'is': 9, 'best': 10}, {'Gfg': 8, 'is': 11, 'best': 19}, {'Gfg': 9, 'is': 16, 'best': 1}]
The required value : 8

Time complexity: O(n), where n is the number of dictionaries in the list. This is because the max function is used to iterate over the entire list to find the maximum value based on the key “K”. The get function has an average time complexity of O(1) since it uses a hash table for lookup. Therefore, the overall time complexity of this code is O(n). 
Auxiliary space: O(1), as it only uses a constant amount of extra space to store the result.

Method #2 : Using max() + external function

This is yet another way to solve this problem. This computes in similar way as above method, just the difference being of usage of custom comparator rather than lambda function.




# Python3 code to demonstrate working of
# Extract ith Key's Value of K's Maximum value dictionary
# Using max() + external function
 
# custom function as comparator
def cust_fnc(ele):
    return ele.get(K, 0)
 
# initializing lists
test_list = [{"Gfg" : 3, "is" : 9, "best" : 10},
             {"Gfg" : 8, "is" : 11, "best" : 19},
             {"Gfg" : 9, "is" : 16, "best" : 1}]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing K
K = "best"
 
# initializing i
i = "Gfg"
 
# using get() to handle missing key, assigning lowest value
res = max(test_list, key = cust_fnc)[i]
     
# printing result
print("The required value : " + str(res))

Output
The original list : [{'Gfg': 3, 'is': 9, 'best': 10}, {'Gfg': 8, 'is': 11, 'best': 19}, {'Gfg': 9, 'is': 16, 'best': 1}]
The required value : 8

Time complexity: O(n), where n is the length of the list of dictionaries.
Auxiliary space: O(1), since only a constant amount of extra space is used for the variables K, i, and res. 

Method #3 : Using max() and for loops




# Python3 code to demonstrate working of
# Extract ith Key's Value of K's Maximum value dictionary
 
 
# initializing lists
test_list = [{"Gfg" : 3, "is" : 9, "best" : 10},
            {"Gfg" : 8, "is" : 11, "best" : 19},
            {"Gfg" : 9, "is" : 16, "best" : 1}]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing K
K = "best"
 
# initializing i
i = "Gfg"
x=[]
for j in test_list:
    x.append(j[K])
a=max(x)
for j in test_list:
    if(j[K]==a):
        res=j[i]   
# printing result
print("The required value : " + str(res))

Output
The original list : [{'Gfg': 3, 'is': 9, 'best': 10}, {'Gfg': 8, 'is': 11, 'best': 19}, {'Gfg': 9, 'is': 16, 'best': 1}]
The required value : 8

Time Complexity : O(N*N)
Auxiliary Space : O(N)

Method 4: Using list comprehension:




# initializing lists
test_list = [{"Gfg": 3, "is": 9, "best": 10},
             {"Gfg": 8, "is": 11, "best": 19},
             {"Gfg": 9, "is": 16, "best": 1}]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing K
K = "best"
 
# initializing i
i = "Gfg"
 
# extracting values of K's key from the test_list using list comprehension
k_values = [d[K] for d in test_list]
 
# finding the maximum value of K's key
max_k_value = max(k_values)
 
# extracting the dictionary that contains K's maximum value using list comprehension
max_k_dict = [d for d in test_list if d[K] == max_k_value][0]
 
# extracting the ith key's value from the dictionary
res = max_k_dict[i]
 
# printing result
print("The required value : " + str(res))

Output
The original list : [{'Gfg': 3, 'is': 9, 'best': 10}, {'Gfg': 8, 'is': 11, 'best': 19}, {'Gfg': 9, 'is': 16, 'best': 1}]
The required value : 8

Time Complexity: O(N), where n is the number of dictionaries in the test_list. 
Auxiliary Space: O(N)

Method #5: Using a loop and if statements




test_list = [{"Gfg" : 3, "is" : 9, "best" : 10},
             {"Gfg" : 8, "is" : 11, "best" : 19},
             {"Gfg" : 9, "is" : 16, "best" : 1}]
 
# initializing K
K = "best"
 
# initializing i
i = "Gfg"
 
max_val = float('-inf')
res = None
 
for d in test_list:
    if K in d and d[K] > max_val:
        max_val = d[K]
        res = d[i]
 
print("The required value : " + str(res))

Output
The required value : 8

Time complexity: O(n), where n is the length of the test_list. We need to iterate through all the dictionaries in the list to find the maximum value of K.
Auxiliary space: O(1). We are only using a few variables to store the maximum value and the corresponding key’s value, so the space used is constant.

Method#6: Using Recursive method.

The algorithm for the recursive method to extract the value of key i from the dictionary with the maximum value of key K in a list of dictionaries is as follows:

  1. Define a function extract_max_value that takes in five arguments: test_list, K, i, max_val, and res.
  2. Check if test_list is empty.
  3. If test_list is empty, return res.
  4. Otherwise, check if key K is present in the first dictionary in test_list and if its value is greater than max_val.
  5. If key K is present in the first dictionary in test_list and its value is greater than max_val, update max_val to the value of key
  6. K in the first dictionary and update res to the value of key i in the first dictionary. Then call extract_max_value recursively with the remaining dictionaries in test_list.
  7. Otherwise, call extract_max_value recursively with the remaining dictionaries in test_list.




def extract_max_value(test_list, K, i, max_val=float('-inf'), res=None):
    if not test_list:
        return res
    elif K in test_list[0] and test_list[0][K] > max_val:
        return extract_max_value(test_list[1:], K, i, test_list[0][K], test_list[0][i])
    else:
        return extract_max_value(test_list[1:], K, i, max_val, res)
 
test_list = [{"Gfg" : 3, "is" : 9, "best" : 10},
             {"Gfg" : 8, "is" : 11, "best" : 19},
             {"Gfg" : 9, "is" : 16, "best" : 1}]
K = "best"
i = "Gfg"
 
res = extract_max_value(test_list, K, i)
print("The required value : " + str(res))

Output
The required value : 8

The time complexity of this algorithm is O(n), where n is the number of dictionaries in test_list. This is because we need to iterate over all dictionaries in test_list to find the maximum value of key K.

The auxiliary space of this algorithm is O(n), where n is the number of dictionaries in test_list. This is because we need to store n recursive calls on the call stack.

Method #7: Using the built-in sorted() function

  1. Define a function extract_max_value_sorted() that takes in the same parameters as extract_max_value(): test_list, K, i, max_val=float(‘-inf’), and res=None.
  2. Inside the function, sort the test_list in descending order based on the value associated with the K key using the sorted() function with a key argument that returns the K value of each dictionary.
  3. Loop through the sorted list and find the first dictionary that has a K key equal to or greater than the current max_val value.
  4. If a dictionary with a greater K value is found, update max_val and res to the values associated with the K and i keys of the current dictionary, respectively.
  5. Return the final value of res.




def extract_max_value_sorted(test_list, K, i, max_val=float('-inf'), res=None):
    sorted_list = sorted(test_list, key=lambda x: x[K], reverse=True)
    for item in sorted_list:
        if item[K] >= max_val:
            max_val = item[K]
            res = item[i]
    return res
 
# Initializing list
test_list = [{"Gfg" : 3, "is" : 9, "best" : 10},
             {"Gfg" : 8, "is" : 11, "best" : 19},
             {"Gfg" : 9, "is" : 16, "best" : 1}]
# Initializing values
K = "best"
i = "Gfg"
 
res = extract_max_value_sorted(test_list, K, i)
 
# Printing the result
print("The required value : " + str(res))

Output
The required value : 8

Time complexity: O(n log n), where n is the length of test_list due to the use of the sorted() function.
Auxiliary space: O(n), due to the creation of a sorted list with the same length as test_list.


Article Tags :