V
V
Viktor Yurchenko2020-08-22 19:15:53
Python
Viktor Yurchenko, 2020-08-22 19:15:53

Why can't get value by key "from" in python list?

All keys except from work, when using "from" it gives an error: KeyError: 'from' and I can also use this key in outputting strings, I assume it's a reserved word, but I don't know how to fix it.
Example Json
{
"id": 280743947,
"state": "EXECUTED",
"date": "2018-09-27T14:26:24.629306",
"operationAmount": {
"amount": "45653.70",
"currency": {
"name": "RUB",
"code": "RUB"
}
},
"description": "Organization transfer",
"

#!/usr/bin/env python3
import json
from operator import attrgetter
todos_by_user = {}
with open("operations.json", "r", encoding = "utf-8") as read_files:
    data = json.load(read_files)
print(len(data))
data = [trans for trans in data if trans ] #избавляемся от пустых элементов, без этой строчки код внизу будет выдавать ошибку
sorted_data = sorted(data, key=lambda x:x.get('date'), reverse = True)

for trans in data[:1]:
    print(trans, end="\n\n")
    
for trans in sorted_data[:5]:

    print('{date} {description}\n'
          '{from_to} -> {to}\n'
          '{amount} {currency} \n'.format(from_to=trans["from"],  date = trans["date"],description =trans["description"], to=trans['to'],
                                        amount = trans['operationAmount']['amount'], currency = trans['operationAmount']['currency']['name'], )
          )

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Z
zexer, 2020-08-22
@Witosser

d = {'from': 1}
d.get('from', 'not found')

There is no problem to use the word 'from' as a dictionary key, you need to see what you are feeding in the loop as trans

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question