比较python中的两个dict以获得相似键的最大值

比较python中的两个dict以获得相似键的最大值,python,dictionary,compare,Python,Dictionary,Compare,我有两条格言: a={"test1":90, "test2":45, "test3":67, "test4":74} b={"test1":32, "test2":45, "test3":82, "test4":100} 如何提取同一密钥的最大值以获取新dict,如下所示: c={"test1":90, "test2":45, "test3":82, "test4":100} 试试这个: >>> a={"test1":90, "test2":45, "te

我有两条格言:

a={"test1":90,  "test2":45,  "test3":67,  "test4":74}
b={"test1":32,  "test2":45,  "test3":82,  "test4":100}
如何提取同一密钥的最大值以获取新dict,如下所示:

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={ k:max(a[k],b[k]) for k in a if b.get(k,'')}
{'test1': 90, 'test3': 82, 'test2': 45, '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}

不是最好的,但仍然是一种变体:

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}

到目前为止,您尝试了什么?请给出您的代码,您试图获得此结果吗?我认为您缺少属于
b
的键,但不属于
a
。我们需要元素包含在两个目录中。所以,如果b中有一个,而a中没有,我们就不能执行max运算