Python – Maximum of filtered Keys in dictionary
Last Updated :
27 Apr, 2023
Sometimes while working with Python dictionaries, we might have a problem in which we require to just maximum the selective key values from the dictionary. This problem can occur in web development domain. Let’s discuss certain ways in which this problem can be solved.
Method #1: Using list comprehension + get() + max() The combination of the above functions can be used to perform this particular task. In this, we access the values using the get method and traverse the dictionary using list comprehension. We perform maximum using max().
Python3
test_dict = { 'gfg' : 1 , 'is' : 2 , 'best' : 3 , 'for' : 4 , 'CS' : 5 }
print ("The original dictionary : " + str (test_dict))
key_list = [ 'gfg' , 'best' , 'CS' ]
res = max ([test_dict.get(key) for key in key_list])
print ("The maximum of Selective keys : " + str (res))
|
Output :
The original dictionary : {'for': 4, 'gfg': 1, 'is': 2, 'best': 3, 'CS': 5}
The maximum of Selective keys : 5
Time Complexity: O(n), where n is the length of the list test_dict
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method #2 : Using itemgetter() + max() This single function can be used to perform this particular task. It is built in to perform this specific task. It takes chain of keys and returns the corresponding values as a tuple which can be type casted. We perform maximum using max().
Python3
from operator import itemgetter
test_dict = { 'gfg' : 1 , 'is' : 2 , 'best' : 3 , 'for' : 4 , 'CS' : 5 }
print ( "The original dictionary : " + str (test_dict))
key_list = [ 'gfg' , 'best' , 'CS' ]
res = max ( list (itemgetter( * key_list)(test_dict)))
print ( "The maximum of Selective keys : " + str (res))
|
Output
The original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
The maximum of Selective keys : 5
Method #3: Using a lambda function with the map() function:
Step-by-Step Algorithm :
- Initialize a dictionary test_dict with key-value pairs.
- Initialize a list key_list with a selective set of keys from the dictionary.
- Use the map() function with a lambda function to create a new list of values from test_dict corresponding to the keys in key_list.
- For each key in key_list, call the get() method on test_dict with the key as the argument to retrieve the value associated with the key.
- If the key is not present in the dictionary, return float(‘-inf’) as the default value.
- Use the max() function to find the maximum value in the new list of values.
Print the maximum value found in step 4 as the output.
Python
test_dict = { 'gfg' : 1 , 'is' : 2 , 'best' : 3 , 'for' : 4 , 'CS' : 5 }
print ( "The original dictionary : " + str (test_dict))
key_list = [ 'gfg' , 'best' , 'CS' ]
max_value = max ( map ( lambda key: test_dict.get(key, float ( '-inf' )), key_list))
print ( "The maximum of Selective keys : " + str (max_value))
|
Output
The original dictionary : {'CS': 5, 'is': 2, 'gfg': 1, 'best': 3, 'for': 4}
The maximum of Selective keys : 5
Complexity Analysis :
Time Complexity: O(n) where n is the number of keys in the key_list.
This is because the map() function creates a new list of values by applying the lambda function to each key in the key_list and the max() function has a time complexity of O(n). So the overall time complexity of this code is O(n) + O(n) = O(2n) = O(n)
Auxiliary Space: O(n) where n is the number of keys in the key_list.
This is because the map() function creates a new list of values that has the same length as the key_list.
Method #4: Using loop and setdefault()
- Initializing the dictionary test_dict
- Initializing the list of keys to filter key_list.
- setdefault() function returns the value of the key if it exists in the dictionary, else it sets the default value to the key and returns it.
- comparing the value of max_value with the returned value and setting max_value to the greater of the two.
Python3
test_dict = { 'gfg' : 1 , 'is' : 2 , 'best' : 3 , 'for' : 4 , 'CS' : 5 }
print ( "The original dictionary : " + str (test_dict))
key_list = [ 'gfg' , 'best' , 'CS' ]
max_value = 0
for key in key_list:
max_value = test_dict.setdefault(key, max_value)
print ( "The maximum of Selective keys : " + str (max_value))
|
Output
The original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
The maximum of Selective keys : 5
Time Complexity: O(N) where N is the number of items in the dictionary.
Space Complexity: O(1), as we are not using any extra memory.
Method#5: Using a for loop and try-except block
- Initialize a variable maximum with the minimum possible value using float(‘-inf’).
- Traverse through each key of the key_list using a for loop.
- Inside the loop, try to access the value of the current key in test_dict using try and except block.
- If the value of the current key is greater than maximum, update the maximum value with the current value of the key.
- Print the maximum value of the selected keys using print().
Python3
test_dict = { 'gfg' : 1 , 'is' : 2 , 'best' : 3 , 'for' : 4 , 'CS' : 5 }
print ( "The original dictionary : " + str (test_dict))
key_list = [ 'gfg' , 'best' , 'CS' ]
maximum = float ( '-inf' )
for key in key_list:
try :
if test_dict[key] > maximum:
maximum = test_dict[key]
except :
pass
print ( "The maximum of Selective keys : " + str (maximum))
|
Output
The original dictionary : {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'CS': 5}
The maximum of Selective keys : 5
Time Complexity: O(N) where N is the number of items in the dictionary.
Auxiliary Space: O(1), as we are not using any extra memory.
Similar Reads
Get Maximum of Each Key Dictionary List - Python
We are given a list of dictionaries and our task is to find the maximum value for each key across all dictionaries. If a key appears in multiple dictionaries we take the highest value among them. For example: a = [{'a': 3, 'b': 8}, {'a': 10, 'b': 2, 'c': 5}, {'c': 12, 'a': 7}] then the output will b
3 min read
Filter List Of Dictionaries in Python
Filtering a list of dictionaries is a fundamental programming task that involves selecting specific elements from a collection of dictionaries based on defined criteria. This process is commonly used for data manipulation and extraction, allowing developers to efficiently work with structured data b
2 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
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 met
2 min read
Filter List of Python Dictionaries by Key in Python
In Python, filtering a list of dictionaries based on a specific key is a common task when working with structured data. In this article, weâll explore different ways to filter a list of dictionaries by key from the most efficient to the least. Using List Comprehension List comprehension is a concise
3 min read
Python | Filter Tuple Dictionary Keys
Sometimes, while working with Python dictionaries, we can have itâs keys in form of tuples. A tuple can have many elements in it and sometimes, it can be essential to get them. If they are a part of a dictionary keys and we desire to get filtered tuple key elements, we need to perform certain functi
4 min read
Python - Maximum record value key in dictionary
Sometimes, while working with dictionary records, we can have a problem in which we need to find the key with maximum value of a particular key of nested records in list. This can have applications in domains such as web development and Machine Learning. Lets discuss certain ways in which this task
6 min read
Python | Prefix key match in dictionary
Sometimes, while working with dictionaries, we can have a problem in which we need to find the dictionary items that have some constraints on keys. One such constraint can be a prefix match on keys. Let's discuss certain ways in which this task can be performed. Method #1: Using dictionary comprehen
6 min read
Python - Extract Maximum Keys' value dictionaries
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
6 min read
Get first K items in dictionary = Python
We are given a dictionary and a number K, our task is to extract the first K key-value pairs. This can be useful when working with large dictionaries where only a subset of elements is needed. For example, if we have: d = {'a': 1, 'b': 2, 'c': 3, 'd': 4} and K = 2 then the expected output would be:
2 min read