简体   繁体   中英

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 ie 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}

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM