2014-03-13 63 views
-1

我有這個嵌套的字典,我想檢查值是否匹配,如果他們不返回值。比較來自字典python的字典值

dict_test = {'sct2': {(5, 5, 0): [1, 2, 3]}, 'sct1': {(5, 5, 0): [1, 2, 4]}} 

所以從迭代直通dict_test我會比較來自「SCT2」和「SCT1」字典的值,看看它們是否匹配,如果他們不,我會打印出didnt匹配值基本相符。我能做到這一點,如果我分成2個詞典和比對它們進行比較

test1=dict_test['sct2'] 
test2=dict_test['sct1'] 

,比我可以比較2個字典,做這樣的事情:

mismatch = [val for val in test1.itervalues() if not val in test2.itervalues()] 

將返回[1,2 ,4]雖然我希望它返回4而不是列表

我想知道是否有更好的方法來做到這一點,而不必創建2個字典,任何幫助表示讚賞。謝謝

+0

所以你想比較'''[1,2,3]''''''[1,2,4]'''? – wnnmaw

+0

你只想比較具有相同元組鍵的條目嗎? –

+2

你的例子似乎並沒有使用test2,但確實使用了undefined y;這聽起來不對...... –

回答

0

使用minus operator of sets,它給出了兩組的差異。爲了清楚起見,您可以使用差異方法來代替,這也會產生差異。

mismatch = list(filter(set(s2)-set(s1) for s1 in dict_test["sct2"].values()\ 
      for s2 in dict_test["sct1"].values())) 
+0

減號運算符需要顯式轉換爲一個集合。 – IceArdor

+0

@IceArdor True;我認爲負運算符和差分方法是相同的。然而,差異方法將's1'隱式轉換爲一個集合,而負運算符則不會。將提交關於該問題的錯誤報告(或增強請求)。 –

+0

沒有必要將's2'中的鍵轉換爲一個集合...使用's2.viewkeys() - s1'來利用dict視圖對象,它的'-' *將*與任意可迭代一起使用。 –

0

沒有你正在試圖解決這個問題的一個更好的主意,這裏的代碼,將根據您的test_dict返回((3,4))。如果您想要更好地解決您的問題的答案,請清楚地說明您的問題,限制和要求。

def diffList(a,b): 
    '''Assumption: a and b are same length 
    Returns non-matching ordered pairs of a and b 
    ''' 
    return filter(lambda ai, bi: ai != bi, zip(a,b))) 

outerKeyPairs = [(outerKeyA, outerKeyB) for outerKeyA in test_dict for outerKeyB in test_dict if outerKeyA > outerKeyB] 
for outerKeyA, outerKeyB in outerKeyPairs: 
    for innerKey in test_dict[outerKeyA]: 
     if innerKey in test_dict[outerKeyB]: 
      yield diffList(test_dict[outerKeyA][innerKey], test_dict[outerKeyB][innerKey]) 
0

一個相當乾淨的方式來做到這一點是:

def diff_list(l1, l2): 
    s = set(l2) 
    return [i for i in l1 if i not in s] 

{t:diff_list(l1, test2[t]) for (t,l1) in test1.iteritems()} 

這將產生每個不同的鍵的映射與值的列表被丟失:

{(5, 5, 0): [3]} 

請注意,上述diff_list的邏輯假設您不關心ea中物品的位置和數量通道列表。如果這是很重要的,diff_list可以實現爲:

def diff_list(l1, l2): 
    return {i: (v[0], v[1]) for i,v in enumerate(map(None, l1, l2)) if v[0] != v[1]} 

使用這種方法,你會得到以下輸出:

>>> test1 # Here's what test1 looks like 
{(5, 5, 0): [1, 2, 3]} 

>>> test2 # Here's what test2 looks like 
{(5, 5, 0): [1, 2, 4]} 

>>> {t:diff_list(l1, test2[t]) for (t,l1) in test1.iteritems()} # Getting the difference 
{(5, 5, 0): {2: (3, 4)}} 

也就是說,你得到包含test1每一個不同的密鑰字典和test2,映射到包含每個不同索引的字典以及這兩個不同列表中該索引處的值。