Last active
November 14, 2016 08:50
-
-
Save mattstabeler/9f7a72f7bd188824bbd6180bc4a70bc8 to your computer and use it in GitHub Desktop.
Python check object keys exists
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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"]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Probably a one line lambda expression that does the same, but this is easier to understand