简体   繁体   中英

Sorting Dictionary Items Using Python

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.

值错误

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

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] ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM