2016-04-15 52 views
1

我想剥离一个嵌套的字典(只有1级深度,例如:some_dict = {'a':{}, b:{}}所有非零值和无值
但是,我不确定谁重新组装字典,下面给我一个关键的错误剥离非零值的嵌套字典

def strip_nested_dict(self, some_dict): 
    new_dict = {} 
    for sub_dict_key, sub_dict in some_dict.items(): 
     for key, value in sub_dict.items(): 
      if value: 
       new_dict[sub_dict_key][key] = value 
    return new_dict 
+0

请提供示例输入和所需输出 – wim

回答

1

您需要创建嵌套的字典访问之前:

for sub_dict_key, sub_dict in some_dict.items(): 
    new_dict[sub_dict_key] = {} # Add this line 

    for key, value in sub_dict.items(): 
     # no changes 

(为了new_dict[sub_dict_key][key]工作,new_dict必须b e字典,& new_dict[sub_dict_key]也必须是字典。)

0

这工作。耻辱你不能只分配一个嵌套的值,而不必先为每个键创建一个空的。

def strip_nested_dict(self, some_dict): 
    new_dict = {} 
    for sub_dict_key, sub_dict in some_dict.items(): 
     new_dict[sub_dict_key] = {} 
     for key, value in sub_dict.items(): 
      if value: 
       new_dict[sub_dict_key][key] = value 
    return new_dict