if else nested for loops using python list comprehension

Viewed 3317

Can anyone help me figure the list comprehension way of producing following output -

Let given list be -

results = [
    {"id":  1, "name":  "input"},
    {"name": "status", "desc": "Status"},
    {"name": "entity", "fields": [
        {"id": 101, "name": "value"},
        {"id": 102, "name": "address"}]
    }
]

And I am looking for output in the form of list. The code to get the output is:

output = []
for eachDict in results:
    if "fields" in eachDict:
        for field in eachDict["fields"]:
            output.append(eachDict["name"]+"."+field["name"])
    else:
        output.append(eachDict["name"])

Thus the output using above code is -

['input', 'status', 'entity.value', 'entity.address']

Is it possible to get similar output using if else nested for loops in list Comprehension?

I am having trouble trying to get access to that inner for loop in if condition of list Comprehension

My attempt -

output = [eachDict["name"]+"."+field["name"] for field in eachDict["fields"] if "fields" in eachDict else eachDict["name"] for eachDict in results]
2 Answers
Related