2016-04-15 70 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