[Solved] Using yield in nested loop


As you’ve been told in the comments, I also don’t think you can save memory using yield in this case. However, if you only want to know how to use yield, this is one of the options:

import pandas as pd

data = [{
    "id": 123,
    "sports": {
        "football": {
            "amount": 3,
            "count": 54
        },
        "baseball": {
            "amount": 4,
            "count": 67
        }
    }
}]
result = []


def yield_data(sports):
    for sport_name, sport_item in sports.items():
        yield sport_item, sport_name


for d in data:
    for row, row['kind'] in yield_data(d['sports']):
        row['id'] = d['id']
        result.append(row)

result = pd.DataFrame(result)
print(result)

solved Using yield in nested loop