Comparing two dict in python to get the maximum value for a 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 a new dict like below:

c={"test1":90,  "test2":45,  "test3":82,  "test4":100}

      

+3


source to share


3 answers


You can try 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}

      

+7


source


Try the following:



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

      

+1


source


Not the best, but another option:

from itertools import chain

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

c = dict(sorted(chain(a.items(), b.items()), key=lambda t: t[1]))
assert c == {'test1': 90, 'test2': 45, 'test3': 82, 'test4': 100, 'test5': 1}

      

0


source







All Articles