Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

171
Views
How to implement Specific field data into one list and Another filed data into another list in Django

I'm using Django 3x. I have one table called Book. When I write a query for this I'm getting data like this:

book_details = Book.objects.all().values()
print(book_details)

<QuerySet [{'id': 1, 'author': 'ABC', 'price': 150, 'category': 'Comic', 'available': 1}, {'id': 2, 'author': 'XYZ', 'price': 500, 'category': 'Historical Fiction', 'available': 1}, {'id': 3, 'author': 'MNO', 'price': 200, 'category': 'Horror', 'available': 0}]>

I'm trying to create data in this below format

{'id':[1,2,3], 'author':['ABC', 'XYZ', 'MNO'], 'price':[150,500,200], 'category':['Comic', 'Historical Fiction', 'Horror'], 'available':[1,1,0]}

How to create data in this format.

Please advise the best way to do this. An explanation would be much appreciated. Thanks!.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

If you do:

lst_of_dicts = list(book_details)

You will obtain the following, so if you print lst_of_dicts it will look like this:

[{'id': 1, 'author': 'ABC', 'price': 150, 'category': 'Comic', 'available': 1},
{'id': 2, 'author': 'XYZ', 'price': 500, 'category': 'Historical Fiction', 'available': 1}, 
{'id': 3, 'author': 'MNO', 'price': 200, 'category': 'Horror', 'available': 0}]

So this is a list of dictionaries, while you want a dict of lists so there is a further step that you must need to do and that is this one:

from itertools import chain   # Necessary import

keys = set(chain(*[dic.keys() for dic in lst_of_dicts ]))
final_dict = {key : [dic[key] for dic in lst_of_dicts if key in dic] for key in keys }

final_dict will look like this:

{'id': [1, 2, 3], 'author': ['ABC', 'XYZ', 'MNO'], 'available': [1, 1, 0], 'price': [150, 500, 200], 'category': ['Comic', 'Historical Fiction', 'Horror']}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!