2014-09-04 129 views
3

最大值我有这两个类型的字典:在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} 
+2

那你试试这么远吗? – Mathias 2014-09-04 06:26:18

+1

你会给你的代码试图达到这个结果吗? – Nilesh 2014-09-04 06:27:14

回答

1

试试这个:

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

我想你错过了'b'而不是'a'的一部分。 – hennes 2014-09-04 06:40:40

+0

我们需要这些元素是在两个字符。所以如果b中有一个不在a中,我们不能执行最大操作 – xecgr 2014-09-04 07:01:51

7

你可以尝试这样的,

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

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

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}