删除包含无值的嵌套字典中的键

时间:2018-01-08 14:04:51

标签: python dictionary nested

我有以下词典:

dict_2 = {
    'key1': {'subkey1': 2, 'subkey2': 7, 'subkey3': 5},
    'key2': {'subkey1': None, 'subkey2': None, 'subkey3': None},
}

我期待从dict_2中的None值中清除subkeys,删除整个密钥及其嵌套字典:

简而言之,我的输出应该是:

dict_2={key1:{subkey1:2,subkey2:7,subkey3:5}}

我尝试的是:

glob_dict={}

for k,v in dict_2.items():
    dictionary={k: dict_2[k] for k in dict_2 if not None (dict_2[k]
['subkey2'])}
    if bool(glob_dict)==False:
        glob_dict=dictionary
    else:
        glob_dict={**glob_dict,**dictionary}

print(glob_dict)

我目前的输出是:

TypeError: 'NoneType' object is not callable

我不确定循环是否是摆脱嵌套循环的None值的最佳方法,我不确定如何表达我想要摆脱{ {1}}值。

2 个答案:

答案 0 :(得分:4)

删除所有SET LANGUAGE us_english 和后续空字符的递归解决方案可以看作:

代码:

None

测试代码:

def remove_empties_from_dict(a_dict):
    new_dict = {}
    for k, v in a_dict.items():
        if isinstance(v, dict):
            v = remove_empties_from_dict(v)
        if v is not None:
            new_dict[k] = v
    return new_dict or None

结果:

dict_2 = {
    'key1': {'subkey1': 2, 'subkey2': 7, 'subkey3': 5},
    'key2': {'subkey1': None, 'subkey2': None, 'subkey3': None},
}
print(remove_empties_from_dict(dict_2))

答案 1 :(得分:1)

dict_2={'key1':{'subkey1':2,'subkey2':7,'subkey3':5} ,'key2':{'subkey1':None,'subkey2':None,'subkey3':None}}

d = {}
for k, v in dict_2.iteritems():
    if any(v.values()):
        d[k] = v
print d

结果:

{'key1': {'subkey2': 7, 'subkey3': 5, 'subkey1': 2}}