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

Sort list of lists of dictionaries by datetime in python

I would like to sort a list of books that is returned by the Google Books API by the date published of the books. The data looks something like this:

{
 "kind": "books#volumes",
 "totalItems": 506,
 "items": [
   {
  ...
     "volumeInfo": {
       "title": "RHYTHM OF WAR PART ONE",
       "authors": [
         "BRANDON SANDERSON"
       ],
       "publishedDate": "2023-03-16",
       "industryIdentifiers": [
         {
           "type": "ISBN_10",
           "identifier": "1473233372"
         },
   ...
   },

What I have tried is first first isolating the books in a new list like so:

myList = myList["items"]

And then sorting the new list by datetime.

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

myListSorted = sorted(myList, key=lambda d: datetime.datetime.strptime(d["volumeInfo"]["publishedDate"], '%Y-%m-%d'))

I am getting the following error message:

myListSorted = sorted(myList, key=lambda d: datetime.datetime.strptime(d["publishedDate"]["volumeInfo"], '%Y-%m-%d'))

TypeError: list indices must be integers or slices, not str

I have also tried using the itemgetter method, but have not been successful so far.

The results of the API calls can be sorted by date published like so:

https://www.googleapis.com/books/v1/volumes?q=inauthor:brandon%20sanderson&orderBy=newest

But I am adding the results of several calls together in one list and would like to be able to sort all of the books by release date.

>Solution :

The problem must be elsewhere in your code, as this does minimally what you said you did, but has no issues:

from json import load
from urllib.request import urlopen
from datetime import datetime

with urlopen('https://www.googleapis.com/books/v1/volumes?q=inauthor:brandon%20sanderson&orderBy=newest') as r:
    data = load(r)
    items = data['items']
    sorted_items = sorted(items, key=lambda d: datetime.strptime(d["volumeInfo"]["publishedDate"], '%Y-%m-%d'))

print(sorted_items)

Please provide a minimal, reproducible example, if you do still have a problem.

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