0

i have a problem;

import requests
import json
from datetime import datetime
result = requests.get("https://api.exchangeratesapi.io/history?start_at=2020-12-1&end_at=2020-12-13&symbols=USD,TRY&base=USD")
result = json.loads(result.text)
print(result["rates"])
print(sorted(i, key=lambda date: datetime.strptime(date, "%Y-%m-%d")))

And i added the error in the below. I want to sort the dates.

ValueError

Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
  • 1
    The variable `i` is missing? – Dani Mesejo Dec 14 '20 at 15:34
  • 1
    Welcome to SO! Check out the [tour]. Please provide a [mre] as text, not pictures. As part of that, please provide the JSON itself, instead of the `requests.get()` call. You can [edit] the question. Please also use a more descriptive title while you're there. – wjandrea Dec 14 '20 at 15:41
  • Yes @DaniMesejo , i = dict((x, y) for x, y in result.items()) i didn't add it to my code editor. Thanks wjandrea , i got it. – Alican Akca Dec 14 '20 at 18:39

2 Answers2

1

The variable i has no meaning here, you can do

ra = result["rates"]
ra = sorted(ra, key=lambda date: datetime.strptime(date, "%Y-%m-%d"))
print(ra)

This will return a list because dict has no order in Python(always!), you can not put any order on dict elements.

To use a ordered dict, you can try OrderedDict in Python, see

https://docs.python.org/3/library/collections.html#collections.OrderedDict

cesc
  • 65
  • 1
  • 4
0

I think the missing variable i is result? If that's the case, you can do something like this:

sorted_rates = dict(sorted(
  result["rates"].items(),
  key=lambda item: datetime.strptime(item[0], "%Y-%m-%d")))

Here, we first convert the dictionary result["rates"] into an array of tuples of the form (key, value). Then we sort that using a comparator function that gets the string date from the tuple by accessing the first element (item[0]).

comonadd
  • 1,822
  • 1
  • 13
  • 23