【问题标题】:Strip nested dict of non zero values剥离非零值的嵌套字典
【发布时间】:2016-04-15 15:54:33
【问题描述】:

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

【问题讨论】:

  • 请提供示例输入和所需输出

标签: python dictionary


【解决方案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 必须是字典,而new_dict[sub_dict_key] 也必须是字典。)

【讨论】:

    【解决方案2】:

    这行得通。遗憾的是,您不能只分配一个嵌套值,而不必先为每个键创建一个空值。

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-29
      相关资源
      最近更新 更多