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

Dealing with scope in a recursive Python function

I have a JSON input file that looks like this:

{"nodes": [
    {"properties": {
        "id": "rootNode",
        "name": "Bertina Dunmore"},
      "nodes": [
        {"properties": {
            "id": 1,
            "name": "Gwenneth Rylett",
            "parent_id": "rootNode"},
          "nodes": [
            {"properties": {
                "id": 11,
                "name": "Joell Waye",
                "parent_id": 1}},
            {"properties": {
                "id": 12,
                "name": "Stan Willcox",
                "parent_id": 1}}]},
        {"properties": {
            "id": 2,
            "name": "Delbert Dukesbury",
            "parent_id": "rootNode"},
          "nodes": [
            {"properties": {
                "id": 21,
                "name": "Cecil McKeever",
                "parent_id": 2}},
            {"properties": {
                "id": 22,
                "name": "Joy Obee",
                "parent_id": 2}}]}]}]}

I want to get the nested properties dictionaries into a (flat) list of dictionaries. Creating a recursive function that will read this dictionaries is easy:

def get_node(nodes):
    for node in nodes:
        print(node['properties'])
        if 'nodes' in node.keys():
            get_node(node['nodes'])

Now, I’m struggling to append these to a single list:

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

def get_node(nodes):
    prop_list = []
    for node in nodes:
        print(node['properties'])
        prop_list.append(node['properties'])
        if 'nodes' in node.keys():
            get_node(node['nodes'])
    return prop_list

This returns [{'id': 'rootNode', 'name': 'Bertina Dunmore'}], even though all properties dictionaries are printed. I suspect that this is because I’m not handling the function scope properly.

Can someone please help me get my head around this?

>Solution :

You need to combine the prop_list returned by the recursive call with the prop_list in the current scope. For example,

def get_node(nodes):
    prop_list = []
    for node in nodes:
        print(node['properties'])
        prop_list.append(node['properties'])
        if 'nodes' in node.keys():
            prop_list.extend(get_node(node['nodes']))
    return prop_list
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