简体   繁体   中英

Get Child Key Value of Nested Dictionary without Parent Key(s)

Seems to be many questions like this but I can't find this specific answer. Let's say I have a dictionary like so:

{"keyA": 
  {"a": "blue", "b": {"b1": "sky", "b2": "baby", "b3": "navy"},

"keyB": 
  {"x": "horse", "y": {"y1": "stallion", "y2": "thoroughbred"}, "z": {"z1": "white", "z2": "black"}}       

"keyC": "father"
 }

Is there any easy way to get the value of 'z1' (or any nested key) if I DO NOT KNOW it's parent key or the location of the parent key within the dictionary?

I was thinking a recursive function where I pass 'z1' as the key I'm searching for and it runs through the dictionary until there is a match, but I haven't been able to get that to work.

Making a recursive function is a good guess:

data = {'keyA':
  {'a': 'blue', 'b': {'b1': 'sky', 'b2': 'baby', 'b3': 'navy'},

'keyB':
  {'x': 'horse', 'y': {'y1': 'stallion', 'y2': 'thoroughbred'}, 'z': {'z1': 'white', 'z2': 'black'}},

'keyC': 'father'
 }}



def find_value(data, key):
    if not isinstance(data, dict):
        return None

    try:
        return data[key]
    except KeyError:
        for sub_data in data.values():
            sub_value = find_value(sub_data, key)
            if sub_value is not None:
                return sub_value

    return None

print(find_value(data, 'z1'))
# 'white'

print(find_value(data, 'z4'))
# None

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM