[Answered ]-Can I create 2 dictionary from only one loop over queryset

1👍

One approach:

booking_data = {}
vehicle_type_mapping = {}
for r in vehicle_category.types.all():
    vehicle_type_mapping[r.id] = r
    booking_data[r] = 0

an alternative:

booking_data = dict.fromkeys(vehicle_category.types.all(), 0)
vehicle_type_mapping = {k.id: k for k in booking_data}

Both solutions call vehicle_category.types.all() only once, instead of twice.

Leave a comment