Home > Blockchain >  Sort list of lists of dictionaries by datetime in python
Sort list of lists of dictionaries by datetime in python

Time:12-23

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.

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 sanderson&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.

CodePudding user response:

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 sanderson&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.

CodePudding user response:

I figured out your problem!

In your second myListSorted statement, you got the dictionary arguments the wrong way around!

Try this:

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