Created
February 23, 2017 18:38
-
-
Save martinburch/1531e86294ad06fcbe7226f923551cf5 to your computer and use it in GitHub Desktop.
recursive function to get value from dictionary given a list of nested keys
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
#!/usr/bin/env python | |
# encoding: utf-8 | |
def nestedGet(d,p): | |
if len(p) > 1: | |
try: | |
return nestedGet(d.get(p[0]),p[1:]) | |
except AttributeError: | |
return None | |
if len(p) == 1: | |
try: | |
return d.get(p[0]) | |
except AttributeError: | |
return None | |
print nestedGet({"a":{"b":{"c":1}}},["a","b","c"]) | |
print nestedGet({"a":{"bar":{"c":1}}},["a","b","c"]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment