2014-09-04 103 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}