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

Time:09-15

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

CodePudding user response:

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)

CodePudding user response:

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}

CodePudding user response:

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)

CodePudding user response:

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

CodePudding user response:

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}

CodePudding user response:

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