Skip to content
Related Articles
Open in App
Not now

Related Articles

Python Program that displays the key of list value with maximum range

Improve Article
Save Article
Like Article
  • Last Updated : 10 Mar, 2023
Improve Article
Save Article
Like Article

Given a Dictionary with keys and values that are lists, the following program displays key of the value whose range in maximum.

Range = Maximum number-Minimum number

Input : test_dict = {“Gfg” : [6, 2, 4, 1], “is” : [4, 7, 3, 3, 8], “Best” : [1, 0, 9, 3]} 
Output : Best 
Explanation : 9 – 0 = 9, Maximum range compared to all other list given as values
Input : test_dict = {“Gfg” : [16, 2, 4, 1], “Best” : [1, 0, 9, 3]} 
Output : Gfg 
Explanation : 16 – 1 = 15, Maximum range compared to all other list given as values
 

Method 1 : Using max(), min() and loop 

In this, we get max() and min() of each list and perform difference to find range. This value is then stored and max difference of all such values is computed by applying max() at the result list.

Python3




# initializing dictionary
test_dict = {"Gfg" : [6, 2, 4, 1], "is" : [4, 7, 3, 3, 8], "Best" : [1, 0, 9, 3]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
max_res = 0
for sub, vals in test_dict.items():
     
    # storing maximum of difference
    max_res = max(max_res, max(vals) - min(vals))   
    if max_res == max(vals) - min(vals):
        res = sub
         
# printing result
print("The maximum element key : " + str(res))


Output:

The original dictionary is : {‘Gfg’: [6, 2, 4, 1], ‘is’: [4, 7, 3, 3, 8], ‘Best’: [1, 0, 9, 3]}

The maximum element key : Best

Time Complexity: O(n) where n is the number of elements in the dictionary “test_dict”. The sorted and itemgetter function is used to perform the task and it takes O(nlogn) time.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the dictionary “test_dict”. 

Method 2 : Using list comprehension, max() and min() 

In this, we compute the maximum range, and then extract the key which matches that difference using list comprehension.

Python3




# initializing dictionary
test_dict = {"Gfg" : [6, 2, 4, 1], "is" : [4, 7, 3, 3, 8], "Best" : [1, 0, 9, 3]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# getting max value
max_res = max([max(vals) - min(vals) for sub, vals in test_dict.items()])
 
# getting key matching with maximum value
res = [sub for sub in test_dict if max(test_dict[sub]) - min(test_dict[sub]) == max_res][0]
 
# printing result
print("The maximum element key : " + str(res))


Output:

The original dictionary is : {‘Gfg’: [6, 2, 4, 1], ‘is’: [4, 7, 3, 3, 8], ‘Best’: [1, 0, 9, 3]}

The maximum element key : Best


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!