Python – Display the key of list value with maximum range

PythonServer Side ProgrammingProgramming

When it is required to display the key of list value with maximum range, a simple iteration is used.

Example

Below is a demonstration of the same −

my_dict = {"pyt" : [26, 12, 34, 21], "fun" : [41, 27,43, 53, 18], "learning" : [21, 30, 29, 13]}

print("The dictionary is :")
print(my_dict)

max_result = 0

for sub, values in my_dict.items():
   max_result = max(max_result, max(values) - min(values))
   if max_result == max(values) - min(values):
      result = sub

print("The result is :")
print(result)

Output

The dictionary is :
{'pyt': [26, 12, 34, 21], 'fun': [41, 27, 43, 53, 18], 'learning': [21, 30, 29, 13]}
The result is :
fun

Explanation

  • A dictionary is defined and displayed on the console.

  • A variable is initialized to 0.

  • The dictionary elements are iterated over, and the ‘max’ method is used to get the maximum of the difference between the ‘max’ and ‘min’ elements and the previously determined maximum value.

  • If the maximum element is equal to difference between the ‘max’ and ‘min’ elements, the element is considered as result.

  • This is the output that is displayed on the console.

raja
Updated on 08-Sep-2021 09:01:00

Advertisements