We are given a list of dictionaries and our task is to find the maximum value for each key across all dictionaries. If a key appears in multiple dictionaries we take the highest value among them. For example: a = [{'a': 3, 'b': 8}, {'a': 10, 'b': 2, 'c': 5}, {'c': 12, 'a': 7}] then the output will be {'a': 10, 'b': 8, 'c': 12}
Using defaultdict
We can use defaultdict(int) to store the maximum values for each key while iterating through the list of dictionaries.
from collections import defaultdict
a = [{'a': 3, 'b': 8}, {'a': 10, 'b': 2, 'c': 5}, {'c': 12, 'a': 7}]
res = defaultdict(int)
for d in a:
for k, v in d.items():
res[k] = max(res[k], v)
print(dict(res))
Output
{'a': 10, 'b': 8, 'c': 12}
Explanation:
- We use defaultdict(int) which initializes missing keys with 0 (since int() returns 0).
- We iterate through each dictionary and compare each key’s value with the existing maximum then the max() function ensures that only the highest value is stored for each key.
Using Counter
We can use collections.Counter to store and update the maximum values dynamically.
from collections import Counter
a = [{'a': 3, 'b': 8}, {'a': 10, 'b': 2, 'c': 5}, {'c': 12, 'a': 7}]
res = Counter()
for d in a:
for k, v in d.items():
res[k] = max(res[k], v)
print(dict(res))
Output
{'a': 10, 'b': 8, 'c': 12}
Explanation:
- Counter behaves like a dictionary but starts with default values of 0, similar to defaultdict(int).
- We iterate through each dictionary and update the maximum value for each key.
- max_values[k] = max(max_values[k], v) ensures that the highest value is always stored.
Using Dictionary Comprehension
We can use dictionary comprehension combined with max() to find the maximum value for each key.
a = [{'a': 3, 'b': 8}, {'a': 10, 'b': 2, 'c': 5}, {'c': 12, 'a': 7}]
res = {k: max(d.get(k, float('-inf')) for d in a) for k in {key for d in a for key in d}}
print(res)
Output
{'a': 10, 'c': 12, 'b': 8}
Using pandas.DataFrame
If the dictionary list is large then we can use Pandas to efficiently compute the maximum for each key.
import pandas as pd
a = [{'a': 3, 'b': 8}, {'a': 10, 'b': 2, 'c': 5}, {'c': 12, 'a': 7}]
df = pd.DataFrame(arr)
res = df.max().to_dict()
print(res)
{'a': 10.0, 'b': 8.0, 'c': 12.0}Explanation:
- We create a Pandas DataFrame from the list of dictionaries and df.max() finds the maximum values for each column (key).
- .to_dict() converts the result back into a dictionary.