python - 去除非零值的嵌套字典

标签 python dictionary

我正在尝试剥离一个嵌套字典(只有 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/

相关文章:

python - 为什么我不能跳出 while 循环?

python - Python 倒排索引

R构造文档术语矩阵如何匹配其值由空格分隔的短语组成的字典

python - 如何反序列化 python 打印的字典?

python - .get 和字典

python - Pyarrow s3fs 按时间戳分区

python - 将所有PDF文件转换为目录中的文本

python - 为 read_csv 中的 Pandas 索引列指定转换器

python - 创建形状为 (None, 1) 的有序整数的张量

python - 为什么在 string.format() 字典引用中不需要 '?