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 program to get maximum of each key Dictionary List
When working with a list of dictionaries, you often need to find the maximum value for each key across all dictionaries. Python provides several approaches to accomplish this task efficiently.
Using Simple Iteration
The most straightforward approach uses nested loops to iterate through each dictionary and track the maximum value for each key ?
my_list = [{"Hi": 18, "there": 13, "Will": 89},
{"Hi": 53, "there": 190, "Will": 87}]
print("The list is:")
print(my_list)
my_result = {}
for elem in my_list:
for key, val in elem.items():
if key in my_result:
my_result[key] = max(my_result[key], val)
else:
my_result[key] = val
print("The result is:")
print(my_result)
The list is:
[{'Hi': 18, 'there': 13, 'Will': 89}, {'Hi': 53, 'there': 190, 'Will': 87}]
The result is:
{'Hi': 53, 'there': 190, 'Will': 89}
Using Dictionary Comprehension with max()
A more concise approach uses dictionary comprehension to extract all values for each key and find the maximum ?
my_list = [{"Hi": 18, "there": 13, "Will": 89},
{"Hi": 53, "there": 190, "Will": 87}]
# Get all unique keys
all_keys = set().union(*(d.keys() for d in my_list))
# Find maximum value for each key
my_result = {key: max(d[key] for d in my_list if key in d) for key in all_keys}
print("The result is:")
print(my_result)
The result is:
{'there': 190, 'Hi': 53, 'Will': 89}
Using defaultdict
The collections.defaultdict can simplify the logic by automatically handling missing keys ?
from collections import defaultdict
my_list = [{"Hi": 18, "there": 13, "Will": 89},
{"Hi": 53, "there": 190, "Will": 87}]
my_result = defaultdict(lambda: float('-inf'))
for elem in my_list:
for key, val in elem.items():
my_result[key] = max(my_result[key], val)
# Convert back to regular dict
my_result = dict(my_result)
print("The result is:")
print(my_result)
The result is:
{'Hi': 53, 'there': 190, 'Will': 89}
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| Simple Iteration | High | Good | Clear logic, beginners |
| Dictionary Comprehension | Medium | Better | Concise one-liners |
| defaultdict | High | Best | Large datasets |
Conclusion
Use simple iteration for clear, readable code when dealing with small datasets. For better performance with larger data, consider using defaultdict or dictionary comprehension approaches.
