Trouble undestanding a piece of python code

Viewed 35

I was going through a code and i cant quiet understand this piece of code

def filter_orgs(source):
orgs = [org for o in source["orgs"] if (org := filter_orgs(o))]
if orgs or source["available"]:
    return {
        "org_name": source["org_name"], 
        "orgs": orgs
    }

Usage:

source = {
"org_name": "1",
"available": True,
"orgs": [
    {
        "org_name": "2",
        "available": False,
        "orgs": []
    },
    {
        "org_name": "3",
        "available": False,
        "orgs": []
    },
    {
        "org_name": "4",
        "available": True,
        "orgs": []
    },
    {
        "org_name": "5",
        "available": False,
        "orgs": [
            {
                "org_name": "6",
                "available": False,
                "orgs": []
            },
            {
                "org_name": "7",
                "available": False,
                "orgs": []
            },
            {
                "org_name": "8",
                "available": False,
                "orgs": [
                    {
                        "org_name": "9",
                        "available": False,
                        "orgs": []
                    },
                    {
                        "org_name": "10",
                        "available": True,
                        "orgs": []
                    }
                ]
            }
        ]
    }
]
}

filtered_source = filter_orgs(source)

Output:

{
"org_name": "1",
"orgs": [
    {
        "org_name": "4",
        "orgs": []
    },
    {
        "org_name": "5",
        "orgs": [
            {
                "org_name": "8",
                "orgs": [
                    {
                        "org_name": "10",
                        "orgs": []
                    }
                ]
            }
        ]
    }
]
}

I am new to programming. I know its a recursive function but I cant quiet get what's happening especially orgs = [org for o in source["orgs"] if (org := filter_orgs(o))] can some one care to explain .. Please, Thank you:)

1 Answers
// Function which takes a source of type Dictionary
def filter_orgs_simplified(source: dict) -> dict:
orgs_source: list = source['orgs']
orgs: list = []

for o in orgs_source:
    org = filter_orgs(o)

    if not org:
        continue

    orgs.append(org)

if orgs or source["available"]:
return {
    "org_name": source["org_name"], 
    "orgs": orgs
}

This is the simplified version of the above code.

Actually the function takes a source of type Dictionary and and returns a filtered Dictionary back.

Related