3

I want to create a recursive method with Python that prints this dictionary:

partners = {
        'manager-1': {
            'name': 'Manager 1',
            'children': {
                'manager-2': {
                    'name': 'Manager 2',
                    'children': {
                        'employee-1': {
                            'name': 'Employee 1',
                            'children': {
                                'employee-7': {
                                    'name': 'Employee 7',
                                },
                                'employee-8': {
                                    'name': 'Employee 8',
                                }
                            }
                        },
                        'employee-2': {
                            'name': 'Employee 2',
                        },
                        'employee-3': {
                            'name': 'Employee 3',
                        },
                    },
                },
                'manager-3': {
                    'name': 'Manager 3',
                    'children': {
                        'employee-4': {
                            'name': 'Employee 4',
                        },
                        'employee-5': {
                            'name': 'Employee 5',
                        },
                        'employee-6': {
                            'name': 'Employee 6',
                        },
                    },
                },
                'manager-4': {
                    'name': 'Manager 4',
                },
                'manager-5': {
                    'name': 'Manager 5',
                }
            }
        }
    }

And gives it like this:

--Manager 1
----Manager 2
------Employee 1
--------Employee 7
--------Employee 8
------Employee 2
------Employee 3
----Manager 3
------Manager 4
------Manager 5
------Manager 6
----Manager 4
----Manager 5

I made this method:

def hierarch(partners):
    for partner in partners:
        if 'children' not in partner.keys(): 
            print(partner['name'])
        else:
            hierarch(partner['children'])

And I got this error when running the code:

AttributeError: 'str' object has no attribute 'keys'

How can I make a script that allows me to print this hierarchy? I'm not really good with dictionaries. I'm working with Python 3. Any help please? Thanks.

1
  • 5
    Have you tried anything? SO isn't for people to write your code for you. Also why does your expected output not have Employee 7?
    – ninesalt
    Commented Oct 3, 2018 at 11:06

2 Answers 2

5

Do you need to reproduce the exact order? You could use something like this to traverse the data structure:

def recurse(data, level):
    if type(data) is dict:
        if "name" in data:
            print("-" * level + data["name"])
        for (key, value) in data.items():
            recurse(value, level + 1)
recurse(partners, 1)
1
  • A cleaner way to do this would be to have level as a default arg so you don't have to explicitly state in when you initially call the function. def recurse(data, level=1). Also OP's output has +2 dashes per level so maybe increment by 2 and start from 2.
    – ninesalt
    Commented Oct 3, 2018 at 11:20
0

You get that AttributeError because you are recursively calling the hierarch function on every 'children' value. That's valid for the keys like 'employee-1', since the recursive call will loop over the associated dict, but it will fail on 'name', since there is no associated dict, just a name string.

So you need to test each item to see whether it's valid to recurse on it. You can use the type function for that, but it's recommended to use the more versatile isinstance function.

Rather than printing the desired names, we can make the function more flexible by turning it into a generator. That way we can loop over the generated results, printing them as we go, or perform some other processing. Or we can easily collect them into a list, or a new flat dictionary.

partners = {
    'manager-1': {
        'name': 'Manager 1',
        'children': {
            'manager-2': {
                'name': 'Manager 2',
                'children': {
                    'employee-1': {
                        'name': 'Employee 1',
                        'children': {
                            'employee-7': {
                                'name': 'Employee 7',
                            },
                            'employee-8': {
                                'name': 'Employee 8',
                            }
                        }
                    },
                    'employee-2': {
                        'name': 'Employee 2',
                    },
                    'employee-3': {
                        'name': 'Employee 3',
                    },
                },
            },
            'manager-3': {
                'name': 'Manager 3',
                'children': {
                    'employee-4': {
                        'name': 'Employee 4',
                    },
                    'employee-5': {
                        'name': 'Employee 5',
                    },
                    'employee-6': {
                        'name': 'Employee 6',
                    },
                },
            },
            'manager-4': {
                'name': 'Manager 4',
            },
            'manager-5': {
                'name': 'Manager 5',
            }
        }
    }
}

def show(obj, depth=0):
    depth += 1
    for v in obj.values():
        if isinstance(v, dict):
            yield from show(v, depth)
        else:
            yield v, depth

for v, depth in show(partners):
    print('-' * depth + v)   

output

--Manager 1
----Manager 2
------Employee 1
--------Employee 7
--------Employee 8
------Employee 2
------Employee 3
----Manager 3
------Employee 4
------Employee 5
------Employee 6
----Manager 4
----Manager 5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.