Skip to content

Instantly share code, notes, and snippets.

@mattstabeler
Last active November 14, 2016 08:50
Show Gist options
  • Save mattstabeler/9f7a72f7bd188824bbd6180bc4a70bc8 to your computer and use it in GitHub Desktop.
Save mattstabeler/9f7a72f7bd188824bbd6180bc4a70bc8 to your computer and use it in GitHub Desktop.
Python check object keys exists
# Search an object heirarchy for the presence of the given keys
def keyExists(obj, keys):
first, rest = keys[0], keys[1:]
if first in obj or len(obj) > int(first):
if len(rest) == 0:
return True
return keyExists(obj[first], rest)
return False
# Example
onion = {
"layers" : [
{
"skin" : {
"colour" : "brown",
"depth" : 1
}
},
{
"skin" : "green"
}
]
}
if keyExists(onion, ["layers",0, "skin", "colour"]):
print "the onion has {} skin!".format(onion["layers"][0]["skin"]["colour"])
@mattstabeler
Copy link
Author

Probably a one line lambda expression that does the same, but this is easier to understand

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment