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 – Limit the values to keys in a Dictionary List
When working with a list of dictionaries, you often need to find the minimum and maximum values for each key across all dictionaries. Python provides the min() and max() functions to efficiently limit values to their bounds.
Example
Below is a demonstration of finding min/max values for each key ?
my_list = [{"python": 4, "is": 7, "best": 10},
{"python": 2, "is": 5, "best": 9},
{"python": 1, "is": 2, "best": 6}]
print("The list is :")
print(my_list)
my_result = dict()
keys = list(my_list[0].keys())
for my_elem in keys:
my_result[my_elem] = [min(sub[my_elem] for sub in my_list), max(sub[my_elem] for sub in my_list)]
print("The result is :")
print(my_result)
Output
The list is :
[{'python': 4, 'is': 7, 'best': 10}, {'python': 2, 'is': 5, 'best': 9}, {'python': 1, 'is': 2, 'best': 6}]
The result is :
{'python': [1, 4], 'is': [2, 7], 'best': [6, 10]}
How It Works
A list of dictionaries is defined with three dictionaries containing the same keys
An empty dictionary
my_resultis created to store the resultsThe keys from the first dictionary are extracted using
keys()methodFor each key, we use generator expressions with
min()andmax()to find boundsThe result stores each key mapped to a list containing [minimum_value, maximum_value]
Alternative Approach Using Dictionary Comprehension
You can achieve the same result more concisely using dictionary comprehension ?
my_list = [{"python": 4, "is": 7, "best": 10},
{"python": 2, "is": 5, "best": 9},
{"python": 1, "is": 2, "best": 6}]
result = {key: [min(d[key] for d in my_list), max(d[key] for d in my_list)]
for key in my_list[0].keys()}
print("The result is :")
print(result)
The result is :
{'python': [1, 4], 'is': [2, 7], 'best': [6, 10]}
Conclusion
Use min() and max() with generator expressions to efficiently find value bounds across dictionary lists. Dictionary comprehension provides a more concise alternative for the same operation.
