Python Check if Key Exists in Deeply Nested Dictionary or List of Dictionaries, Without Knowing the Path

Depth First Search (DFS) for Key Verification in Python Dictionary and List.

I'm open to new opportunities! For a full-time role, contract position, or freelance work, reach out at talha@talhaawan.net or LinkedIn.

The Python code below recursively goes through the nested dictionary (also known as hash and object in other languages), an array of dictionaries, or both, to check if the given key exists or not, without knowing the path to the key in advance.

This is pretty much the replication of the JavaScript code for verifying if the key exists in deeply nested objects and arrays I had written several years ago.

Code

def doesKeyExist (hash, key):
    if(type(hash) != dict and type(hash) != list):
        return False
    elif key in hash:
        return True
    elif(type(hash) == list):
        for item in hash:
            result = doesKeyExist(item, key)
            if (result):
                return result
    else:
        for item in hash:
            result = doesKeyExist(hash[item], key)
            if (result):
                return result
    return False

Sample Data

def add(a, b):
    return a + b

deeplyNestedHash = {
    "A": {
        "B": {
            "C": {
                "D": {
                    "E": "Eeee",
                    "F": "Efff",
                    "G": {
                        "Gee": None,
                        "H": {},
                        "addMethod": add
                    },
                    "aList": [
                        {
                            "id": 1,
                            "name": "John"
                        },
                        {
                            "id": 2,
                            "name": "Smith"
                        },
                        {
                            "id": 3,
                            "name": "Ross",
                            "info": ("Ross", 8, "History", 3.5)
                        }
                    ],
                    "theSet": {1,2,3,4,5, "Hello"},
                    "someDates": {"1999-01-01": {"users": 9999}, "2021": "Euro Cup"}
                }
            }
        }
    },
    "X": {
        "Y": "",
        "Z": "Zee"
    }
}

Test Results

Running the above sample data with the given code gives us these correct results:

print(doesKeyExist(deeplyNestedHash, "A")) # True
print(doesKeyExist(deeplyNestedHash, "B")) # True
print(doesKeyExist(deeplyNestedHash, "C")) # True
print(doesKeyExist(deeplyNestedHash, "aList")) # True
print(doesKeyExist(deeplyNestedHash, "2021")) # True
print(doesKeyExist(deeplyNestedHash, "1999-01-01")) # True
print(doesKeyExist(deeplyNestedHash, "info")) # True
print(doesKeyExist(deeplyNestedHash, "Z")) # True
print(doesKeyExist(deeplyNestedHash, "firstName")) # False
print(doesKeyExist(deeplyNestedHash, "lastName")) # False
print(doesKeyExist(deeplyNestedHash, "X1")) # False
print(doesKeyExist(deeplyNestedHash, "Zee")) # False

Note that even if you make deeplyNestedHash a list of single hash at the root by enclosing the whole hash in [], the results will be the same.




See also

When you purchase through links on techighness.com, I may earn an affiliate commission.
We use cookies to enhance your experience. By continuing to visit this site you agree to our use of cookies. More info cookie script