How to find the outer keys in a nested dictionary

I have a large nested JSON in python, which I’ve converted to a dictionary. In it, there’s a key called ‘achievements’ in some sub-dictionary (don’t know how far it’s nested). This sub-dictionary is itself either an element of a list, or the value of a key in a larger dictionary.

Assuming all I know is that this key is called ‘achievements’, how can I get its value? It’s fine to assume that the key’s ‘achievements’ name is unique in the entire dictionary at all levels.

>Solution :

One way to get the value associated with the ‘achievements’ key in a large nested dictionary is to use a recursive function that searches through the dictionary at every level. Here’s an example of such a function:

def find_achievements(data):
    if isinstance(data, dict):
        if 'achievements' in data:
            return data['achievements']
            for value in data.values():
                result = find_achievements(value)
                if result is not None:
                    return result
    elif isinstance(data, list):
        for element in data:
            result = find_achievements(element)
            if result is not None:
                return result

achievements = find_achievements(your_dictionary)

This function will search through the dictionary, looking for a key called ‘achievements’. If it finds it, it will return the value associated with that key. If it doesn’t find it, it will recursively search through any nested dictionaries or lists until it finds the key or runs out of elements to search. If it doesn’t find the key at all, it will return None.

You can then use this function to search through your dictionary and get the value associated with the ‘achievements’ key.

Leave a Reply