Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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']
        else:
            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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading