[英]Sort list of lists of dictionaries by datetime in python
我想按圖書出版日期對 Google Books API 返回的圖書列表進行排序。 數據看起來像這樣:
{
"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"
},
...
},
我嘗試過的是首先將書籍隔離在一個新列表中,如下所示:
myList = myList["items"]
然后按日期時間對新列表進行排序。
myListSorted = sorted(myList, key=lambda d: datetime.datetime.strptime(d["volumeInfo"]["publishedDate"], '%Y-%m-%d'))
我收到以下錯誤消息:
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
我也嘗試過使用 itemgetter 方法,但到目前為止還沒有成功。
API 調用的結果可以按發布日期排序,如下所示:
https://www.googleapis.com/books/v1/volumes?q=inauthor:brandon%20sanderson&orderBy=newest
但是我將幾個調用的結果一起添加到一個列表中,並希望能夠按發布日期對所有書籍進行排序。
問題必須在您的代碼中的其他地方,因為這與您所說的一樣,但沒有問題:
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)
如果您仍然有問題,請提供一個最小的、可重現的示例。
我發現你的問題了!
在你的第二個myListSorted
語句中,你得到了字典 arguments 錯誤的方式!
嘗試這個:
myListSorted = sorted(myList, key=lambda d: datetime.datetime.strptime(d["volumeInfo"]["publishedDate"], '%Y-%m-%d'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.