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
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 ]}
print ( "The original dictionary is : " + str (test_dict))
K = 3
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 )
res = []
for idx, ele in enumerate (temp):
res.append(temp[idx][ 0 ])
if temp[idx][ 1 ] ! = temp[idx + 1 ][ 1 ]:
break
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
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 ]}
print ( "The original dictionary is : " + str (test_dict))
K = 3
temp = max (test_dict[key][K] if K < len (
test_dict[key]) else - 1 for key in test_dict)
res = []
for key in test_dict:
if K < len (test_dict[key]) and test_dict[key][K] = = temp:
res.append(key)
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
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 ]}
print ( "The original dictionary is : " + str (test_dict))
K = 3
max_val = - 1
res = []
for key, val in test_dict.items():
if K < len (val):
if val[K] > max_val:
max_val = val[K]
res = [key]
elif val[K] = = max_val:
res.append(key)
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
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 ]}
print ( "The original dictionary is : " + str (test_dict))
K = 3
extracted_values = list ( map ( lambda x: x[K] if K < len (
x) else - float ( 'inf' ), test_dict.values()))
max_val = max (extracted_values)
res = [key for key, val in test_dict.items() if K < len (val)
and val[K] = = max_val]
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
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 ]}
print ( "The original dictionary is : " + str (test_dict))
K = 3
heap = []
for val in test_dict.values():
if K < len (val):
heapq.heappush(heap, - val[K])
max_val = - heapq.heappop(heap)
res = [key for key, val in test_dict.items() if K < len (val) and val[K] = = max_val]
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.
Share your thoughts in the comments
Please Login to comment...