HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonModerate

Get value from dictionary given a list of nested keys

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
valuelistnestedgetkeysdictionaryfromgiven

Problem

I would like to get a deeply-nested value, for example {"a":{"b":{"c":"myValue"}} by providing the keys to traverse. I tried chaining together .get() but that didn't work for cases where some of the keys were missing—in those cases, I want to get None instead.

Could this solution be improved?

#!/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"]) #1
print nestedGet({"a":{"bar":{"c":1}}},["a","b","c"]) #None

Solution

Unless I'm missing something you'd like to implement, I would go for a simple loop instead of using recursion:

def nested_get(input_dict, nested_key):
    internal_dict_value = input_dict
    for k in nested_key:
        internal_dict_value = internal_dict_value.get(k, None)
        if internal_dict_value is None:
            return None
    return internal_dict_value

print(nested_get({"a":{"b":{"c":1}}},["a","b","c"])) #1
print(nested_get({"a":{"bar":{"c":1}}},["a","b","c"])) #None

Code Snippets

def nested_get(input_dict, nested_key):
    internal_dict_value = input_dict
    for k in nested_key:
        internal_dict_value = internal_dict_value.get(k, None)
        if internal_dict_value is None:
            return None
    return internal_dict_value

print(nested_get({"a":{"b":{"c":1}}},["a","b","c"])) #1
print(nested_get({"a":{"bar":{"c":1}}},["a","b","c"])) #None

Context

StackExchange Code Review Q#156144, answer score: 13

Revisions (0)

No revisions yet.