Open In App

Python – Key with Maximum element at Kth index in Dictionary Value List

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

Given a dictionary with values as lists, the task is to write a Python program to get the key with the maximum element at the Kth index by comparing the elements of each list.

Input : test_dict = {'Gfg' : [4, 6, 8, 2], 
'is' : [1, 4, 5, 9], 
'best' :[2, 3, 4, 10], 
'for' :[4, 5, 2, 1], 
'geeks' :[2, 10, 1, 8]}, K = 3 
Output : best 
Explanation : 2, 9, 10, 1, 8 are elements and 10 is maximum.
Input : test_dict = {'Gfg' : [4, 6, 8, 2], 
'is' : [1, 4, 5, 9], 
'best' :[2, 3, 4, 10], 
'for' :[4, 5, 2, 1], 
'geeks' :[2, 10, 1, 8]}, K = 2 
Output : Gfg 
Explanation : 8, 5, 4, 2, 1 are elements and 8 is maximum. 

Method 1 : Using sorted(), dictionary comprehension and lambda

In this, we perform reverse sort of all the list elements at the index K values along with its Key, and then output keys of maximum value extracted.

Example:

Python3




# Python3 code to demonstrate working of
# Key with Maximum element at Kth index
# in Dictionary Value List Using sorted()
# + dictionary comprehension + lambda
 
# initializing dictionary
test_dict = {'Gfg': [4, 6],
             'is': [1, 4, 5, 9, 4, 5, 7],
             'best': [2, 3, 4, 10],
             'for': [4],
             'geeks': [2, 10, 1, 10]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing K
K = 3
 
# sorted sorting all the values in reverse order
# Maximum element is found at 1st position
temp = sorted({key: val[K] if K <= len(val) else -1 for key,
               val in test_dict.items()}.items(),
              key=lambda sub: sub[1], reverse=True)
 
# getting all maximum keys in case of multiple
res = []
for idx, ele in enumerate(temp):
    res.append(temp[idx][0])
    if temp[idx][1] != temp[idx + 1][1]:
        break
 
# printing result
print("The extracted key : " + str(res))


Output

The original dictionary is : {'Gfg': [4, 6], 'is': [1, 4, 5, 9, 4, 5, 7], 'best': [2, 3, 4, 10], 'for': [4], 'geeks': [2, 10, 1, 10]}
The extracted key : ['best', 'geeks']

Time complexity: O(n log n), where n is the total number of elements in the dictionary. 
Auxiliary space: O(n), where n is the total number of elements in the dictionary.

Method 2 : Using max() and generator expression

In this, we perform task of getting maximum using max(), and generator expression is used to iterate through all the keys in dictionary. At next step, we get all the keys matching the maximum element at K.

Example:

Python3




# Python3 code to demonstrate working of
# Key with Maximum element at Kth index
# in Dictionary Value List Using max()
# + generator expression
 
# initializing dictionary
test_dict = {'Gfg': [4, 6, 8, 2, 5, 6],
             'is': [1],
             'best': [2, 3, 4, 10],
             'for': [4, 5, 2, 1],
             'geeks': [2, 10, 1, 10]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing K
K = 3
 
# sorted sorting all the values in reverse order
# Maximum element is found at 1st position
# getting maximum
temp = max(test_dict[key][K] if K < len(
    test_dict[key]) else -1 for key in test_dict)
 
# getting all keys with maximum.
res = []
for key in test_dict:
    if K < len(test_dict[key]) and test_dict[key][K] == temp:
        res.append(key)
 
# printing result
print("The extracted key : " + str(res))


Output

The original dictionary is : {'Gfg': [4, 6, 8, 2, 5, 6], 'is': [1], 'best': [2, 3, 4, 10], 'for': [4, 5, 2, 1], 'geeks': [2, 10, 1, 10]}
The extracted key : ['best', 'geeks']

Time complexity: O(n), where n is the total number of elements in the dictionary values.
Auxiliary space: O(1), as only a constant amount of extra space is used for storing variables.

Method 3: Using loop

Loops through each key-value pair in the dictionary and checks if the Kth index exists in the value list. If it exists, it checks if the current value is greater than the maximum value seen so far (initialized to -1). If it is greater, it updates the maximum value and sets the result to be the current key. If it is equal to the maximum value seen so far, it appends the current key to the result list.

Python3




# initializing dictionary
test_dict = {'Gfg': [4, 6],
             'is': [1, 4, 5, 9, 4, 5, 7],
             'best': [2, 3, 4, 10],
             'for': [4],
             'geeks': [2, 10, 1, 10]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing K
K = 3
 
max_val = -1
res = []
 
# loop through each key-value pair in dictionary
for key, val in test_dict.items():
 
    # check if Kth index exists in value list
    if K < len(val):
 
        # check if current value is greater than max_val
        if val[K] > max_val:
            max_val = val[K]
            res = [key]
 
        # check if current value is equal to max_val
        elif val[K] == max_val:
            res.append(key)
 
# printing result
print("The extracted key : " + str(res))


Output

The original dictionary is : {'Gfg': [4, 6], 'is': [1, 4, 5, 9, 4, 5, 7], 'best': [2, 3, 4, 10], 'for': [4], 'geeks': [2, 10, 1, 10]}
The extracted key : ['best', 'geeks']

Time complexity: O(N), where N is the total number of elements in all value lists of the dictionary.
Auxiliary space: O(1), because it only uses a constant amount of space to store the maximum value seen so far and the result list. 

Method 4:  Using the built-in function map() with lambda function and max() method.

Step-by-step approach:

  • Extract the Kth element of each list value in the dictionary using map() function and lambda function.
  • Find the maximum value in the extracted elements using max() method.
  • Iterate through the dictionary and extract the keys whose Kth element is equal to the maximum value.
    • Append the extracted keys to the res list.
  • Print the res list.

Below is the implementation of the above approach:

Python3




# initializing dictionary
test_dict = {'Gfg': [4, 6],
             'is': [1, 4, 5, 9, 4, 5, 7],
             'best': [2, 3, 4, 10],
             'for': [4],
             'geeks': [2, 10, 1, 10]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing K
K = 3
 
# extract the Kth element of each list value in the dictionary using map() function and lambda function
extracted_values = list(map(lambda x: x[K] if K < len(
    x) else -float('inf'), test_dict.values()))
 
# find the maximum value in the extracted elements
max_val = max(extracted_values)
 
# iterate through the dictionary and extract the keys whose Kth element is equal to the maximum value
res = [key for key, val in test_dict.items() if K < len(val)
       and val[K] == max_val]
 
# printing result
print("The extracted key : " + str(res))


Output

The original dictionary is : {'Gfg': [4, 6], 'is': [1, 4, 5, 9, 4, 5, 7], 'best': [2, 3, 4, 10], 'for': [4], 'geeks': [2, 10, 1, 10]}
The extracted key : ['best', 'geeks']

Time complexity: O(n log n) for sorting (in the list comprehension approach), or O(n) for iteration and extraction (in the map() approach), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(n) for the res list in both approaches.

Method 5: Using the heapq module in Python. 

Step-by-step approach:

  • Import the heapq module.
  • Create an empty heap using the heapify() function from heapq.
  • Loop through the values in the dictionary and add the Kth element of each value to the heap using the heappush() function from heapq.
  • Pop the maximum element from the heap using the heappop() function from heapq.
  • Loop through the dictionary again and add the keys whose Kth element matches the maximum element to the result list.
  • Print the result list.

Below is the implementation of the above approach:

Python3




import heapq
 
# initializing dictionary
test_dict = {'Gfg': [4, 6],
             'is': [1, 4, 5, 9, 4, 5, 7],
             'best': [2, 3, 4, 10],
             'for': [4],
             'geeks': [2, 10, 1, 10]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing K
K = 3
 
# create an empty heap
heap = []
 
# loop through the values in the dictionary and add the Kth element of each value to the heap
for val in test_dict.values():
    if K < len(val):
        heapq.heappush(heap, -val[K]) # negate to find maximum element
 
# pop the maximum element from the heap
max_val = -heapq.heappop(heap)
 
# loop through the dictionary again and add the keys whose Kth element matches the maximum element to the result list
res = [key for key, val in test_dict.items() if K < len(val) and val[K] == max_val]
 
# printing result
print("The extracted key : " + str(res))


Output

The original dictionary is : {'Gfg': [4, 6], 'is': [1, 4, 5, 9, 4, 5, 7], 'best': [2, 3, 4, 10], 'for': [4], 'geeks': [2, 10, 1, 10]}
The extracted key : ['best', 'geeks']

Time complexity: O(n*logk), where n is the number of values in the dictionary and k is the value of K. 
Auxiliary space: O(k) for the heap.



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

Similar Reads