Skip to content

Instantly share code, notes, and snippets.

@martinburch
Created February 23, 2017 18:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martinburch/1531e86294ad06fcbe7226f923551cf5 to your computer and use it in GitHub Desktop.
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
#!/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