Answer the question
In order to leave comments, you need to log in
How to fix key error while sorting json and read whole file?
Error: KeyError: 'date'
Below is working code, but if you replace data[:50] with data, an error occurs. I need to read all the data from the file, not just 50.
import json
from operator import attrgetter
todos_by_user = {}
with open("operations.json", "r", encoding = "utf-8") as read_file:
data = json.load(read_file)
sorted_data = sorted(data[:50], key=lambda x:x['date'], reverse = True)
{
"id":280743947,
"state":"EXECUTED",
"date":"2018-09-27T14:26:24.629306",
"operationAmount":{
"amount":"45653.70",
"currency":{
"name":"руб.",
"code":"RUB"
}
},
"description":"Перевод организации",
"from":"Счет 23177857685058835559",
"to":"Счет 56363465303962313778"
},
{
"id":185048835,
"state":"EXECUTED",
"date":"2019-05-06T00:17:42.736209",
"operationAmount":{
"amount":"74895.83",
"currency":{
"name":"руб.",
"code":"RUB"
}
},
"description":"Перевод со счета на счет",
"from":"Счет 27921306202254867520",
"to":"Счет 49884962711830774470"
}
Answer the question
In order to leave comments, you need to log in
The thing turned out to be that there were empty elements in the json list and Python could not compare them, the line of code before sorting helped:
data = [trans for trans in data if trans ] #избавляемся от пустых элементов, без этой строчки код внизу будет выдавать ошибку
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question