Skip to content

Instantly share code, notes, and snippets.

@saintsGrad15
Created March 21, 2016 18:18
Show Gist options
  • Save saintsGrad15/90326b50cb6a0ae1032f to your computer and use it in GitHub Desktop.
Save saintsGrad15/90326b50cb6a0ae1032f to your computer and use it in GitHub Desktop.
A function to verify the ordered nesting of dict members
def verify_dict_path(dictionary, *args):
"""
Verify that 'dictionary' contains nested members consistent with the additional arguments to 'verify_dict_path' in order
e.g. For the_dict = {"a" : {"b" : {"c" : 3}}}
verify_dict_path(the_dict, "a", "b", "c") == True
verify_dict_path(the_dict, "a", "b") == True
verify_dict_path(the_dict, "a", "b", "c", "d") == False
verify_dict_path(the_dict, "a", "b", "e") == False
:param dictionary: A dictionary
:param args: An arbitrary number of arguments indicating a path into 'dictionary' to test for existence
:return: bool
"""
# If there are no more args to consider...
if len(args) < 1:
return True # ...return True
else:
# If 'dictionary' is still a dict and the next arg is a member of 'dictionary'...
if isinstance(dictionary, dict) and args[0] in dictionary:
return verify_dict_path(dictionary[args[0]], *args[1:]) # ...return the result of verify_dict_path on the next level deeper in 'dictionary' with the next arg
else: # 'dictionary' is not, in fact, a dictionary OR the next arg is not a member of 'dictionary'
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment