最大值我有这两个类型的字典:在python比较两个字典来获得类似的关键
a={"test1":90, "test2":45, "test3":67, "test4":74}
b={"test1":32, "test2":45, "test3":82, "test4":100}
如何提取最大值为相同的密钥来获得新的字典,因为这下面:
c={"test1":90, "test2":45, "test3":82, "test4":100}
最大值我有这两个类型的字典:在python比较两个字典来获得类似的关键
a={"test1":90, "test2":45, "test3":67, "test4":74}
b={"test1":32, "test2":45, "test3":82, "test4":100}
如何提取最大值为相同的密钥来获得新的字典,因为这下面:
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}
那你试试这么远吗? – Mathias 2014-09-04 06:26:18
你会给你的代码试图达到这个结果吗? – Nilesh 2014-09-04 06:27:14