比较python中的两个dict以获得相似键的最大值
问题描述
我有这两个字典:
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}
解决方案
你可以这样试试,
>>> 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}
相关文章