Get value from asymmetrically nested dict with unique keys

Question:

Say I have a nested dict, with asymmetrical nesting, and no key appearing more than once across the entire nested dict:

d = {
'd1' : {'d11': 'a', 'd12': 'b'},
'd2' : {'d21': 'c', 'd22': {'d221': 'd', 'd222': 'e'}}
}

I would like a function (without a module) that returns the value of any of the (unique) keys, i.e.:

def get_some_val(d, key):
    ...
    return val_of_that_key

Anyone who could help me in the right direction? Thanks!

I tried passing the (nested) keys as strings, and then using exec to get the value, but this did not work

Asked By: Max

||

Answers:

One approach:

d = {
    "d1": {"d11": 'a', "d12": 'b'},
    "d2": {"d21": 'c', "d22": {"d221": 'd', "d222": 'e'}}
}


def nested_find(needle, haystack):
    if needle in haystack:
        return haystack[needle]
    for v in haystack.values():
        if isinstance(v, dict):
            val = nested_find(needle, v)
            if val:
                return val


res = nested_find("d222", d)
print(res)

Output

e

A one-liner alternative is to do:

def nested_find(needle, haystack):
    gen = (val for v in haystack.values() if isinstance(v, dict) and (val := nested_find(needle, v)))
    return haystack.get(needle, next(gen, None)) 
Answered By: Dani Mesejo

If the leaf-keys are truly unique, then you could just flatten the dict:

d = {
    'd1' : {'d11': 'a', 'd12': 'b'},
    'd2' : {'d21': 'c', 'd22': {'d221': 'd', 'd222': 'e'}}
}


def flattendict(d):
    res = {}

    def _flatten_subdict(d, res):
        for k, v in d.items():
            if not isinstance(v, dict):
                res[k] = v
            else:
                _flatten_subdict(v, res)

    _flatten_subdict(d, res)
    return res

print(flattendict(d))

which prints

{'d11': 'a', 'd12': 'b', 'd21': 'c', 'd221': 'd', 'd222': 'e'}

ie. a dictionary with only the unique keys.

Answered By: thebjorn
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.