I am new to Python and I was wondering if there was a way I could shorten/optimise the below loops:
JavaScript
x
8
1
for breakdown in data_breakdown:
2
for data_source in data_source_ids:
3
for camera in camera_ids:
4
if (camera.get("id") == data_source.get("parent_id")) and (data_source.get("id") == breakdown.get('parent_id')):
5
for res in result:
6
if res.get("camera_id") == camera.get("id"):
7
res.get('data').update({breakdown.get('name'): breakdown.get('total')})
8
I tried this oneliner, but it doesn’t seem to work:
JavaScript
1
2
1
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'))
2
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:
JavaScript
1
9
1
from itertools import product
2
3
for b, d, c in product(data_breakdown, data_source_ids, camera_ids):
4
if c["id"] != d["parent_id"] or d["id"] != b["parent_id"]:
5
continue
6
for res in result:
7
if res["camera_id"] == c["id"]:
8
res['data'][b['name']] = b['total']
9