Home > Back-end >  Recursively convert Dictionary to List of lists
Recursively convert Dictionary to List of lists

Time:12-31

I have a dictionary

{
    "school_1": {
        "Class_1": {
            "Stud1": "Surname1",
            "Stud2": "Surname2"
        },
        "Class_2": {
            "Stud1": "Surname3",
            "Stud2": "Surname4"
        }
    },
    "school_2": {
        "Class_1": {
            "Stud1": "Surname5",
            "Stud2": "Surname6"
        },
        "Class_2": {
            "Stud1": "Surname7",
            "Stud2": "Surname8"
        }
    }
}

I am trying to create a def that recursively will return a list of lists as below:

[['Surname1', 'Surname2'],['Surname3', 'Surname4'],['Surname5', 'Surname6'],['Surname7', 'Surname8']]

By found examples, I made the def below,

def dict_to_list(dict_to_list):
    list = []
    if isinstance(dict_to_list, dict):
        for k,v in dict_to_list.items():
            dict_to_list(v)
    else:
        list.append(dict_to_list)

    print(list)
    return list

But received result is different at all:

['Surname1']
['Surname2']
[]
['Surname3']
['Surname4']
[]
[]
['Surname5']
['Surname6']
[]
['Surname7']
['Surname8']
[]
[]
[]
[]

CodePudding user response:

Maybe simple list comprehension will be enough?

dct = {
    "school_1": {
        "Class_1": {"Stud1": "Surname1", "Stud2": "Surname2"},
        "Class_2": {"Stud1": "Surname3", "Stud2": "Surname4"},
    },
    "school_2": {
        "Class_1": {"Stud1": "Surname5", "Stud2": "Surname6"},
        "Class_2": {"Stud1": "Surname7", "Stud2": "Surname8"},
    },
}

out = [list(dd.values()) for d in dct.values() for dd in d.values()]
print(out)

Prints:

[
    ["Surname1", "Surname2"],
    ["Surname3", "Surname4"],
    ["Surname5", "Surname6"],
    ["Surname7", "Surname8"],
]

If you want a recursion:

def get_values(o):
    if isinstance(o, dict):
        if all(isinstance(v, str) for v in o.values()):
            yield list(o.values())
        else:
            for v in o.values():
                yield from get_values(v)


out = list(get_values(dct))
print(out)
  • Related