V
V
Viktor Yurchenko2020-08-21 17:42:00
Python
Viktor Yurchenko, 2020-08-21 17:42:00

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)


json:
{
   "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

2 answer(s)
V
Victor Yurchenko, 2020-08-22
@Witosser

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 ] #избавляемся от пустых элементов, без этой строчки код внизу будет выдавать ошибку

D
Dr. Bacon, 2020-08-21
@bacon

It would be necessary to know such basics, the get method of a dictionary. Well, you will teach how to read the docks or google this element of destruction.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question