2

I have a python dict, and some (but not all) of its values are also dicts.

For example:

    d = {'a' : 1,
         'b' : {'c' : 3, 'd' : 'target_value'}
        }

What would be the best way to pass in keys to reach any target value? Something like retrieve(d, (key, nested_key, ...)) where retrieve(d, ('b','d')) would return target value.

3
  • Where are you getting the crazy data structure from? Commented Aug 1, 2016 at 17:38
  • I am parsing a file and organizing it into dictionaries which are sometimes nested. But this applies to any nested indexable data structures. Commented Aug 1, 2016 at 17:40
  • My mistake, retrieve(d, ('b', 'd')) should return target_value Commented Aug 1, 2016 at 17:48

1 Answer 1

2

The better option here is to find a way to normalize your data structure, but if you can't for some reason, you can just access each key in order.

For example:

def nested_getter(dictionary, *keys):
    val = dictionary[keys[0]]
    for key in keys[1:]:
        val = val[key]
    return val
d = {'a' : 1,
     'b' : {'c' : 3, 'd' : 'target_value'}
    }
print(nested_getter(d, 'b', 'd'))

You could also do it recursively:

def nested_getter(dictionary, *keys):
    val = dictionary[keys[0]]
    if isinstance(val, dict):
        return nested_getter(val, *keys[1:])
    else:
        return val
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.