我正在尝试剥离一个嵌套字典(只有 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
最佳答案
您需要在访问嵌套字典之前创建它:
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
必须是字典,并且 new_dict[sub_dict_key]
code> 也必须是字典。)
关于python - 去除非零值的嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36651719/