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

Dictionary Recursive indenting

I have the following code that tries to cover most cases of a dictionary walk, and output it as indented text (indent based on the items’ nesting in the dictionary. There are two problems:

  1. I think the check at the start, which caters for "raw_list", is a bit of a hack, but I cannot think of a better way
  2. I cannot get the level variable to properly reflect its position

Thanks. I think the rest of the recursion is correct…

a = {
    "raw_list" : [1,2,3],
    "a" : 1,
    "b" : 2,
    "mydict": {
        "c":3,
        "d":4
    },
    "mydict2": {
        "c":5,
        "d":6
    },
    "list1": [
        {
            "e1":7, 
            "e2":8
        },
        {
            "e3":9, 
            "e4":10
        }
    ],
    "list2": [
        {
            "f1":11, 
            "f2":12
        }
    ]
}

def process_data(data,level):

    if not isinstance(data,list) and not isinstance(data,dict) :
        print("\t"*level + str(data))
        return

    for element, val in data.items():
        if isinstance(val, dict):
            print("\t"*level + "DICT:" + element)
            level+=1
            process_data(val,level)
        elif isinstance(val, list):
            print("\t"*level + "LIST:" + element)
            level += 1
            for i, item in enumerate(val):
                process_data(item,level)
        else:
            print("\t"*level+element + ":" + str(val))

    level-=1

process_data(a,1)

Got this:

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

LIST:test
    1
    2
    3
    a:1
    b:2
    DICT:mydict
        c:3
        d:4
        DICT:mydict2
            c:5
            d:6
            LIST:list1
                e1:7
                e2:8
                e3:9
                e4:10
                LIST:list2
                    f1:11
                    f2:12

But want this:

LIST:test
    1
    2
    3
a:1
b:2
DICT:mydict
    c:3
    d:4
DICT:mydict2
    c:5
    d:6
LIST:list1
    e1:7
    e2:8
    e3:9
    e4:10
LIST:list2
    f1:11
    f2:12

>Solution :

You are incrementing the level for each element in a loop. Instead, try removing level += 1 and pass incremented level into the recursive call: process_data(item, level + 1).

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