Ramakrishna K
Ramakrishna K

Reputation: 49

comparing more than one dict in python to get the maximum value for similar key

Hello Everyone,

I am struck in while solving the below question i.e comparing more than one dict in python to get the maximum value for similar key.Could you please help me to solve this type of question.

Note: Similar kind of question was asked in Stackoverflow but that is only for two dictionaries with all have same size but in my question it is quiet different.

Sample Input:

a={"test1":90,  "test2":45,  "test4":74}

b={"test1":32,  "test2":45,  "test3":82,  "test5":100}

c={"test1":78,  "test2":65,  "test3":92,  "test4":90,  "test5":90}

d={"test1":42,  "test2":35,  "test3":62,  "test4":80}

Sample Output:

res={"test1":90,  "test2":65,  "test3":92,  "test4":90,   "test5":100}

Upvotes: 0

Views: 569

Answers (1)

Pasindu Gamarachchi
Pasindu Gamarachchi

Reputation: 566

The following should work:

dicts = [a,b,c,d]
res ={}
for dic in dicts:
    for key in dic.keys():
        if key not in res.keys():
            res[key] = dic[key]
        if dic[key] > res[key]:
            res[key] = dic[key]

Upvotes: 3

Related Questions