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
- How to Extract Numbers From a String in Python
- Replace All Keys of Deeply Nested Objects or Array of Objects in JavaScript
- JavaScript Find Total Time Duration
- JavaScript Generate Your Own Random Number Without Math Random
- Compare Two JavaScript Objects and Get the Updated Keys
- JavaScript Token Bucket Algorithm
- CPU Scheduling Algorithms - JavaScript