Can I create 2 dictionary from only one loop over queryset

Question:

This is my code right now :

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

I wonder if there is a way i can create those 2 dict only with one loop. Or is there another way more efficiently that i can do.

Edited for more context:

    for vehicle_category in VehicleCategory.objects.prefetch_related('types').order_by('name'):
        booking_data = {p: 0 for p in vehicle_category.types.all()}
        vehicle_type_mapping = {k.id: k for k in vehicle_category.types.all()} 
        completed_booking_data[vehicle_category] = booking_data

Answers:

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.

Answered By: Dani Mesejo