Created
September 11, 2018 09:39
-
-
Save joaocarmo/8667b59134998f006dd9d134cc18e1e0 to your computer and use it in GitHub Desktop.
Get nested value from an object (Python 2.x and 3.x compatible)
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 | |
try: | |
from functools import reduce | |
except ImportError: | |
pass | |
# How to use | |
# foo = { "a": "a1", "b": "a2", "c": { "d": "a3" } } | |
# bar = ["c", "d"] | |
# nested_value = get_nested_value(foo, bar) | |
# > "a3" | |
# bar = ["c", "d", "f"] | |
# > None | |
def get_nested_value(nested_object, path_to_value): | |
# Define the accumulator function | |
def acc_fn(obj, key): | |
if obj and hasattr(obj, 'get'): | |
return obj.get(key) | |
# Use the reducer function to do the heavy work | |
return reduce(acc_fn, path_to_value, nested_object) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment