How to get maximum values of all the keys in the list of dictonary

Viewed 84

I am facing an issue with getting the maximum of each key in an list of dictionary. for example I have a list of dictionaries ls:

ls = [{'a':2, 'b':4, 'c':7}, {'a':5, 'b': 2, 'c':6}, {'a':1, 'b': 3, 'c':8}]

The output should be {a = 5, b = 4, c = 8}

I have tried a number of methods, for example:

maxx= max(ls, key=lambda x:x['a'])

but this and every other method is returning me the sub-dictonary having the maximum "a" value, b and c is not getting considered

can anyone please help me out on this

7 Answers

Assuming all your dictionaries have the same keys:

{k: max(d[k] for d in ls if k in d) for k in ls[0].keys()}

outputs {'a': 5, 'b': 4, 'c': 8}

I use the keys of the first dictionary ls[0], supposed to be the same as the others

If your dictionaries don't have the same keys, here is a one liner solution (Thank you @Timus for the improvements in the comments)

{k: max(d[k] for d in ls) for k in set().union(*(d.keys() for d in ls)) }

set().union(*(d.keys() for d in ls)) concatenates all keys and select the set of unique keys. max(d[k] for d in ls if k in d) just select the max value if the key is in the dict.

Maybe there is a more elegant solution, but this one works:

ls = [{'a':2, 'b':4, 'c':7}, {'a':5, 'b': 2, 'c':6}, {'a':1, 'b': 3, 'c':8}]

#initialize with first dict
final_dict = ls[0]

for mydict in ls:
    if mydict['a']>final_dict['a']:
        final_dict['a'] = mydict['a']

    if mydict['b']>final_dict['b']:
        final_dict['b'] = mydict['b']

    if mydict['c']>final_dict['c']:
        final_dict['c'] = mydict['c']

print(final_dict)

Not elegant solution, but small.

keys = ls[0].keys()
res = dict()
for key in keys:
    maxvalue = max(ls, key=lambda x:x[key])
    res[key] = maxvalue[key]
-> {'a': 5, 'b': 4, 'c': 8}

This get the work done

maxii = {}
for item in ls:
  for key, value in item.items():
    if key not in maxii:
        maxii[key] = value
    else:
        maxii[key] = max(maxii[key], value)

Create an empty output dictionary then iterate over the remaining items:

ls = [{'a':2, 'b':4, 'c':7}, {'a':5, 'b': 2, 'c':6, 'e':7}, {'a':1, 'b': 3, 'c':8}]

output = {}

for d in ls:
    for k, v in d.items():
        output[k] = max(output.get(k, float('-inf')), v)

print(output)

Output:

{'a': 5, 'b': 4, 'c': 8, 'e': 7}

Assuming the first dictionary contains all the keys, use:

print({k:max(x[k] for x in ls) for k in ls[0].keys()})

Maybe not the cleanest code, but it works:

ls = [{'a':2, 'b':4, 'c':7}, {'a':5, 'b': 2, 'c':6}, {'a':1, 'b': 3, 'c':8}]
complete_dict = {}
for d in ls:
    complete_dict.update(d)

unique_keys = {key for key in complete_dict.keys()}
max_dict = {key: max(ls, key=lambda x: x.get(key, 0)).get(key) for key in unique_keys}
print(max_dict)
Related