2017-08-04 227 views
-4
{'140508921-1183337': {'COVERAGE_PILLAR': nan, 
    'HARDWARE_PILLAR': nan, 
    'SECURITY_PILLAR': nan, 
    'SOFTWARE_PILLAR': nan}, 
'PSS_13240-1451364': {'COVERAGE_PILLAR': 10.0, 
    'HARDWARE_PILLAR': 25.0, 
    'SECURITY_PILLAR': 55.0, 
    'SOFTWARE_PILLAR': 10.0} 
} 

想要刪除具有nan值的鍵。如 「140508921-1183337''should作爲其鑰匙被移除/值對空Python嵌套字典

回答

0

如果a是字典做到這一點:

a={'140508921-1183337': {'COVERAGE_PILLAR': 'nan', 'HARDWARE_PILLAR': 'nan', 'SECURITY_PILLAR':'nan', 'SOFTWARE_PILLAR': 'nan'}, 'PSS_13240-1451364': {'COVERAGE_PILLAR': 10.0, 'HARDWARE_PILLAR': 25.0, 'SECURITY_PILLAR': 55.0, 'SOFTWARE_PILLAR': 10.0}} 


def remove_keys_with_nan(item): 
    if not hasattr(item, 'items'): 
     return item 
    else: 
     d = {key: remove_keys_with_nan(value) for key, value in item.iteritems() if value is not 'nan'} 
     return dict((k, v) for k, v in d.iteritems() if v) 

a = remove_keys_with_nan(a) 

print(a) 

結果:

{'PSS_13240-1451364': {'COVERAGE_PILLAR': 10.0, 'HARDWARE_PILLAR': 25.0, 'SOFTWARE_PILLAR': 10.0, 'SECURITY_PILLAR': 55.0}} 

編輯 - 新問題的新答案

使用:

import numpy as np 

nan = np.nan 

a={'140508921-1183337': {'COVERAGE_PILLAR': nan, 'HARDWARE_PILLAR': nan, 'SECURITY_PILLAR': nan, 'SOFTWARE_PILLAR': nan}, 'PSS_13240-1451364': {'COVERAGE_PILLAR': 10.0, 'HARDWARE_PILLAR': 25.0, 'SECURITY_PILLAR': 55.0, 'SOFTWARE_PILLAR': 10.0}} 

然後與以前相同的代碼。

+0

需要刪除'''140508921-1183337':{}'這也來自字典。 –

+0

@SoravVerma哦。對。讓我在幾分鐘內編輯我的答案 – sera

+0

@SoravVerma完成!!!!!!! – sera