Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I create 2 dictionary from only one loop over queryset

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading