Home > Enterprise >  How to implement Specific field data into one list and Another filed data into another list in Djang
How to implement Specific field data into one list and Another filed data into another list in Djang

Time:11-25

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!.

CodePudding user response:

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']}
  • Related