Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparing two dict in python to get the maximum value for similar key

I have these 2 dicts:

a={"test1":90,  "test2":45,  "test3":67,  "test4":74}
b={"test1":32,  "test2":45,  "test3":82,  "test4":100}

how to extract the maximum value for the same key to get new dict as this below:

c={"test1":90,  "test2":45,  "test3":82,  "test4":100}
like image 411
Abdulkareem Avatar asked Feb 12 '23 02:02

Abdulkareem


2 Answers

You can try like this,

>>> a={"test1":90, "test2":45, "test3":67, "test4":74} 
>>> b={"test1":32, "test2":45, "test3":82, "test4":100}
>>> c = { key:max(value,b[key]) for key, value in a.iteritems() }
>>> c
{'test1': 90, 'test3': 82, 'test2': 45, 'test4': 100}
like image 175
Adem Öztaş Avatar answered Feb 14 '23 17:02

Adem Öztaş


Try this:

>>> a={"test1":90, "test2":45, "test3":67, "test4":74} 
>>> b={"test1":32, "test2":45, "test3":82, "test4":100}
>>> c={ k:max(a[k],b[k]) for k in a if b.get(k,'')}
{'test1': 90, 'test3': 82, 'test2': 45, 'test4': 100}
like image 37
xecgr Avatar answered Feb 14 '23 16:02

xecgr