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

Getting values from a nested dictionary with recursion

def get_values(d):
    values = []
    for v in d.values():
        if isinstance(v, dict):
            get_values(v)
        else:
            values.append(v)
    return values


a = {4: 1, 6: 2, 7: {8: 3, 9: 4, 5: {10: 5}, 2: 6, 6: {2: 7, 1: 8}}}

print(get_values(a))

The above code is meant to print all the values in a dictionary but I’m not very confident with recursion and its only giving me [1,2] as output. Could someone modify it to provide [1,2,3,4,5,6,7,8] and explain how it was done?

>Solution :

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

You need to add all the values from the recursive call to get_values to the list as well, otherwise you are discarding all the work that the recursive call did.

def get_values(d):
    values = []
    for v in d.values():
        if isinstance(v, dict):
            values.extend(get_values(v))
        else:
            values.append(v)
    return values
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