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

Extract fields in a dynamically nested dictionary in an ordered manner

given the following dictionary – which is dynamically so there could be any level of deepness (nested structure):

data = {
    "level": {
        "system": {
            "text": "A Lorem ipsum colour."
        },
        "board": {
            "core": {
                "text": "Another one."
            }
        }
    },
    "peer": {
        "core": {
            "text": "B Lorem ipsum colour."
        },
        "main": {
            "text": "C Lorem ipsum colour."
        }
    }
}

The goal is to extract the text elements orderd (from top to bottom), the result should be something like:

result = "A Lorem ipsum colour. Another one. B Lorem ipsum colour. C Lorem ipsum colour.

I think I’ve to use some type of recursion but I can’t get it. What I get so far – and what is not working – is the following:

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

for k, v in data.items():
    if isinstance(v, dict):
        # i think i have to continue here on a deeper recursion level
    else:
        return v["text"]

Best regards

>Solution :

def dict_value(val: dict):
    for key, item in val.items():
        if type(item) == dict:
            dict_value(item)
        else:
            print(item)


dict_value(data)
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