python - 从嵌套字典中删除所有 None 值

标签 python json dictionary

我在 json 中有以下嵌套字典示例:

{
  "DICT": {
    "List of dict": [
      { #first dict inside the outer list
        "K1": "V1",
        "K2": "V2",
        "K3": "V3",
        "K4": [
          {
            "K4_1_1": "V4_1"
          },
          {
            "K4_2_1": "V4_2"
          },
          {
            "K4_3_1": null
          }
        ],
        "K5 is a list of Dict": [
          {
            "K5_1_1": "V5_1",
            "K5_1_2": "V5_2",
            "K5_1_3": "V5_3",
            "K5_1_4": "V5_4"
          },
          {
            "K5_2_1": "V5_1",
            "K5_2_2": "V5_2",
            "K5_2_3": "V5_3",
            "K5_2_4": "V5_4"
          }
        ]
      },
      { #second dict in the outerlist
        "K1": "V1",
        "K2": "V2",
        "K3": "V3",
        "K4": [
          {
            "K4_1_1": "V4_1_1"
          },
          {
            "K4_2_1": "V4_2_1"
          }
        ],
        "K5": {
          "K5_1_1": "V_1_1",
          "K5_1_2": "V_1_2",
          "K5_1_3": null,
          "K5_1_4": null
        }
      }
    ]
  }
}

请注意,K4K5总是listdict .我需要摆脱所有 null,无论它们在字典或列表中有多深。所以我写了下面的python函数,但是输出是一样的,都是None值仍然存在:

def RemoveNones(Dict):
    for k, v in Dict.items():
        if type(v) == collections.OrderedDict:
            RemoveNones(v)
        elif type(v) == list:
            for i in v:
                RemoveNones(i)
        else:
            Dict = dict((K,V) for K,V in Dict.items() if V!=None)

我里面的字典不是dict但是<class 'collections.OrderedDict'> .

最佳答案

type() 的语法是这样的:if type(v) is list: (not ==)

所以你想要这样的东西:

import json
from collections import OrderedDict

raw_text = '{"DICT":{"List of dict":[{"K1":"V1","K2":"V2","K3":"V3","K4":[{"K4_1_1":"V4_1"},{"K4_2_1":"V4_2"},{"K4_3_1":null}],"K5 is a list of Dict":[{"K5_1_1":"V5_1","K5_1_2":"V5_2","K5_1_3":"V5_3","K5_1_4":"V5_4"},{"K5_2_1":"V5_1","K5_2_2":"V5_2","K5_2_3":"V5_3","K5_2_4":"V5_4"}]},{"K1":"V1","K2":"V2","K3":"V3","K4":[{"K4_1_1":"V4_1_1"},{"K4_2_1":"V4_2_1"}],"K5":{"K5_1_1":"V_1_1","K5_1_2":"V_1_2","K5_1_3":null,"K5_1_4":null}}]}}'

raw_json = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(raw_text)

def remove_nulls(x):
    if type(x) is list:
        return [remove_nulls(v) for v in x if v is not None]
    elif type(x) is OrderedDict:
        return OrderedDict((k,remove_nulls(v)) for k,v in x.items() if v is not None)
    else:
        return x

de_nullified_json = remove_nulls(raw_json)
print(json.dumps(de_nullified_json, indent=2))

输出:

{
  "DICT": {
    "List of dict": [
      {
        "K1": "V1",
        "K2": "V2",
        "K3": "V3",
        "K4": [
          {
            "K4_1_1": "V4_1"
          },
          {
            "K4_2_1": "V4_2"
          },
          {}
        ],
        "K5 is a list of Dict": [
          {
            "K5_1_1": "V5_1",
            "K5_1_2": "V5_2",
            "K5_1_3": "V5_3",
            "K5_1_4": "V5_4"
          },
          {
            "K5_2_1": "V5_1",
            "K5_2_2": "V5_2",
            "K5_2_3": "V5_3",
            "K5_2_4": "V5_4"
          }
        ]
      },
      {
        "K1": "V1",
        "K2": "V2",
        "K3": "V3",
        "K4": [
          {
            "K4_1_1": "V4_1_1"
          },
          {
            "K4_2_1": "V4_2_1"
          }
        ],
        "K5": {
          "K5_1_1": "V_1_1",
          "K5_1_2": "V_1_2"
        }
      }
    ]
  }
}

关于python - 从嵌套字典中删除所有 None 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51040949/

相关文章:

python - 将 numba 的 dict 类型替换为 python 函数的参数

python 3 : matplotlib plotting four lines with dictionary

python递归字典转换为字符串

php - JSON 输出包括索引号

json - Cocoa - 解析 JSON 字符串

google-app-engine - 无法将 []datastore.PropertyList 传递给 GetMulti 函数(数据存储 : src has invalid type)

python - 如何使用 Python 3.5 在 Windows 10 系统上安装 mbed CLI?

Python nltk统计单词和短语频率

python - 反转字符串中的每个单词

ios - swift 对象映射器 : How to parse array inside of an array