2012-07-20 28 views
0

我有以下2個字典,Comapring字典,列表類型值

d1={"aa":[1,2,3],"bb":[4,5,6],"cc":[7,8,9]} 
d2={"aa":[1,2,3],"bb":[1,1,1,1,1,1],"cc":[7,8]} 

我怎麼能比較這兩個字典,並獲得不匹配的鍵值對的 位置(索引)?由於我正在處理 以及大小約爲2 GB的文件,因此這些字典包含非常大的數據 。如何以優化的方式實現?

回答

1
def getUniqueEntry(dictionary1, dictionary2, listOfKeys): 
    assert sorted(dictionary1.keys()) == sorted(dictionary2.keys()), "Keys don't match" #check that they have the same keys 
    for key in dictionary1: 
     if dictionary1[key] != dictionary2[key]: 
      listOfKeys.append(key) 

當調用功能,第三PARAM listOfKeys是你要存儲密鑰空列表。請注意,將2GB的數據讀入字典需要大量內存,並且很可能會失敗。

0

,這是一個更Python方式:列表擴展會考慮這一點是不相等的兩個字典中的值:

diffrent_keys = [key for key in d1 if d1[key] != d2[key] ]