2015-10-15 102 views
1
dic1 = {'memory':'4','cpu':'2','disk':{'total':'160','swap':'4','/':'26','/var':'7','/tmp':'2'}} 

dic2 = {'memory':8','cpu':'2','disk':{'total':'120,'swap':'4','/':'26','/var':'7','/tmp':'2'}} 

請注意,這兩個字典本身都包含另一個字典。 什麼是最有效的方法來比較每個項目而不做dict1 == dict2?最有效的方法來比較python中的兩個字典

由於我必須看到值的一些%變化。所以剩下的唯一選項就是迭代每個字典項目。是這樣的:

for key1 in dic1: 
    for key2 in dic2: 
     if not isinstance(dic1[key1],dict): 
     #compare cpu & memory here 
     if int(dic1[key1]) > int(dict2[key2]) 
     else: 
      #compare disk(internal dictionary here) 
+0

你想用鑰匙做什麼「磁盤」,它的價值是一本字典? – Kasramvd

+0

同樣,我還需要在「磁盤」字典中查看%更改值。是的,你可以認爲字典和「磁盤」字典中的「鍵」保持不變。 – akhi

回答

0

您可以使用itertools.zip_longest來壓縮的價值和他們在一個列表理解比較:

>>> from itertools import chain,zip_longest 

["do something" if isinstance(i,dict) and all(k<v for k,v in zip_longest(i.values(),j.values())) else "do something" for i,j in zip_longest(dic1.values(),dic2.values())] 

注意的是,這裏根據你的需要,你可以用它代替all你可能正在其他功能有興趣使用any或者您想對數值進行一些算術運算。

+0

我也想比較嵌套字典值。有趣的知道鏈&zip_longest。希望這是用來改善性能 – akhi

+0

@akhi由於你沒有提供你想要做的值,我建議一個一般的方法。檢查編輯! – Kasramvd