简体   繁体   English

使用 Python 对字典项进行排序

[英]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变量i在这里没有意义,你可以这样做

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,).这将返回一个列表,因为 dict 在 Python(always,) 中没有顺序。 you can not put any order on dict elements.您不能对 dict 元素下任何命令。

To use a ordered dict, you can try OrderedDict in Python, see要使用有序字典,您可以尝试 Python 中的OrderedDict ,请参阅

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

I think the missing variable i is result ?我认为缺少的变量iresult 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) .在这里,我们首先将字典result["rates"]转换为(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] ).然后我们使用比较器 function 对其进行排序,该比较器通过访问第一个元素( item[0] )从元组中获取字符串日期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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