Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Display the key of list value with maximum range
When it is required to display the key of list value with maximum range, a simple iteration is used. The range of a list is the difference between its maximum and minimum values.
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_range = 0
result_key = ""
for key, values in my_dict.items():
current_range = max(values) - min(values)
if current_range > max_range:
max_range = current_range
result_key = key
print("The result is :")
print(result_key)
print(f"Maximum range: {max_range}")
Output
The dictionary is :
{'pyt': [26, 12, 34, 21], 'fun': [41, 27, 43, 53, 18], 'learning': [21, 30, 29, 13]}
The result is :
fun
Maximum range: 35
How It Works
The algorithm iterates through each key-value pair in the dictionary:
pyt: Range = max([26, 12, 34, 21]) - min([26, 12, 34, 21]) = 34 - 12 = 22
fun: Range = max([41, 27, 43, 53, 18]) - min([41, 27, 43, 53, 18]) = 53 - 18 = 35
learning: Range = max([21, 30, 29, 13]) - min([21, 30, 29, 13]) = 30 - 13 = 17
The key "fun" has the maximum range of 35, so it is returned as the result.
Alternative Approach Using max() Function
You can also solve this using Python's built-in max() function with a key parameter ?
my_dict = {"pyt" : [26, 12, 34, 21], "fun" : [41, 27, 43, 53, 18], "learning" : [21, 30, 29, 13]}
result_key = max(my_dict, key=lambda k: max(my_dict[k]) - min(my_dict[k]))
max_range = max(my_dict[result_key]) - min(my_dict[result_key])
print(f"Key with maximum range: {result_key}")
print(f"Maximum range: {max_range}")
Key with maximum range: fun Maximum range: 35
Conclusion
To find the key with maximum range, calculate the difference between max and min values for each list. The iterative approach is clear and easy to understand, while using max() with a lambda function provides a more concise solution.
