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

3
  • 1
    The variable i is missing? Commented Dec 14, 2020 at 15:34
  • 1
    Welcome to SO! Check out the tour. Please provide a minimal reproducible example 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. Commented Dec 14, 2020 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. Commented Dec 14, 2020 at 18:39

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your interest!
In CPython 3.6 and Python 3.7 onwards, dictionaries started to preserve order.
Thank you @dmitryguzeev this is the first time I know such thing
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]).

1 Comment

Gotcha! Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.