Home > Enterprise >  Getting values from a nested dictionary with recursion
Getting values from a nested dictionary with recursion

Time:06-23

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?

CodePudding user response:

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
  • Related