Home > Net >  How to check if all values is not None in dict continent list and dict with different format
How to check if all values is not None in dict continent list and dict with different format

Time:09-21

I want to check if dict contains value None knowing that the format is not unique it can the dict content other dict and other list contain dict You can see the example :

{
    "first_name": "test",
    "last_name": "test",
    "cars": [
        {"mark": "test", "type": "12"},
        {"mark": "test2", "type": "7"},
    ],
    "date_created": "2022-05-07",
    "invoice_info": {
        "price": 1233,
        "currency": "EUR",
        "date": [
            {"date_1": "2022-05-07", "info": {"comment": "test", "place": "France"}},
            {"date_2": "2022-06-12", "info": {"comment": None, "place": "France"}},
        ]

    }
}

CodePudding user response:

You have to use a recursive function. If the function receives a dictionary or a list, it loops through the values - otherwise compares the value to None. Here is a quick example:

data = {"foo": "bar"}

def includes_none(node):
    if isinstance(node, dict):
        for _, v in node.items():
            if includes_none(v):
                return True
    elif isinstance(node, list):
        for v in node:
            if includes_none(v):
                return True
    else:
        if node is None:
            return True
    return False

print(includes_none(data))

CodePudding user response:

Minimum code here ;)

def seekNone(node):
    if (isinstance(node, dict) or isinstance(node, list)):
        try: node = node.values()
        except: pass
        for val in node:
            if seekNone(val):
                return True
    return node is None


print(seekNone(your_dict_here))
  • Related