Python - Key with Maximum element at Kth index in Dictionary Value List
Last Updated :
05 Apr, 2023
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))
OutputThe 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))
OutputThe 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))
OutputThe 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))
OutputThe 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))
OutputThe 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.
Similar Reads
Python - K Maximum elements with Index in List
GIven a List, extract K Maximum elements with their indices. Input : test_list = [5, 3, 1, 4, 7, 8, 2], K = 2 Output : [(4, 7), (5, 8)] Explanation : 8 is maximum on index 5, 7 on 4th. Input : test_list = [5, 3, 1, 4, 7, 10, 2], K = 1 Output : [(5, 10)] Explanation : 10 is maximum on index 5. Method
4 min read
Python - Assign keys with Maximum element index
Given Dictionary with value lists, the task is to write a Python program to assign each key with an index of the maximum value in the value list. Examples: Input : test_dict = {"gfg" : [5, 3, 6, 3], "is" : [1, 7, 5, 3], "best" : [9, 1, 3, 5]} Output : {'gfg': 2, 'is': 1, 'best': 0} Explanation : Max
4 min read
Python - Filter dictionaries by values in Kth Key in list
Given a list of dictionaries, the task is to write a Python program to filter dictionaries on basis of elements of Kth key in the list. Examples: Input : test_list = [{"Gfg" : 3, "is" : 5, "best" : 10}, {"Gfg" : 5, "is" : 1, "best" : 1}, {"Gfg" : 8, "is" : 3, "best" : 9}, {"Gfg" : 9, "is" : 9, "best
9 min read
Get key with maximum value in Dictionary
Given a dictionary, our task is to find the key having the maximum value. For Example: We are given a dictionary d = {'Audi':100, 'BMW':1292, 'Jaguar': 210000, 'Hyundai' : 88} then the output will be Jaguar as it is the key with maximum value in dictionary.Using max() with a Key FunctionIn this meth
2 min read
Python - Element Frequency starting with K in dictionary value List
Sometimes while working with a lots of data, we can have a problem in which we have data in form of strings list which are values of dictionary keys and we wish to count occurrences of elements starting with character K. Lets discuss certain ways in which this task can be performed. Method #1 : Usin
5 min read
Python - Test Kth index in Dictionary value list
Sometimes, while working with Python dictionaries, we can have a problem in which we need to test if, throughout the dictionary, the kth index of all values in the dictionary is equal to N. This kind of problem can occur in the web development domain. Let's discuss certain ways in which this problem
9 min read
Python - Elements Maximum till current index in List
Given list with elements, extract element if it's the maximum element till current index. Input : test_list = [4, 6, 7, 8] Output : [4, 6, 7, 8] Explanation : All elements are maximum till their index. Input : test_list = [6, 7, 3, 6, 8, 7] Output : [7, 8] Explanation : 7 and 8 are maximum till thei
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 | Count keys with particular value in dictionary
Sometimes, while working with Python dictionaries, we can come across a problem in which we have a particular value, and we need to find frequency if it's occurrence. Let's discuss certain ways in which this problem can be solved. Method #1: Using loop This problem can be solved using naive method o
5 min read
Python Program to display keys with same values in a dictionary List
Given a list with all dictionary elements, the task is to write a Python program to extract keys having similar values across all dictionaries. Examples: Input : test_list = [{"Gfg": 5, "is" : 8, "best" : 0}, {"Gfg": 5, "is" : 1, "best" : 0}, {"Gfg": 5, "is" : 0, "best" : 0}] Output : ['Gfg', 'best'
5 min read