Skip to content
Advertisement

For loops and conditionals in Python

I am new to Python and I was wondering if there was a way I could shorten/optimise the below loops:

for breakdown in data_breakdown:
    for data_source in data_source_ids:
       for camera in camera_ids:
           if (camera.get("id") == data_source.get("parent_id")) and (data_source.get("id") == breakdown.get('parent_id')):
               for res in result:
                   if res.get("camera_id") == camera.get("id"):
                       res.get('data').update({breakdown.get('name'): breakdown.get('total')})

I tried this oneliner, but it doesn’t seem to work:

res.get('data').update({breakdown.get('name'): breakdown.get('total')}) for camera in camera_ids if (camera.get("id") == data_source.get("parent_id")) and (data_source.get("id") == breakdown.get('parent_id'))

Advertisement

Answer

You can use itertools.product to handle the nested loops for you, and I think (although I’m not sure because I can’t see your data) you can skip all the .get and .update and just use the [] operator:

from itertools import product

for b, d, c in product(data_breakdown, data_source_ids, camera_ids):
    if c["id"] != d["parent_id"] or d["id"] != b["parent_id"]:
        continue
    for res in result:
        if res["camera_id"] == c["id"]:
            res['data'][b['name']] = b['total']
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement