尝试按字段对 JSON 进行排序会引发 TypeError



我一直在研究一个 Python 程序,该程序从 API 获取数据,然后将其存储在.json文件中,然后它通过当前时间进行排序并找到周末。如果 WaveHeight 高于 2.00,它将发送电子邮件。

到目前为止,电子邮件系统还可以正常工作,但唯一没有的是本节 -

sorted(data, key = lambda i: i['hours']) #sorts through cache_file data 
print([0])

运行脚本时出现此错误 -

sorted (data, key = lambda i: i['hours']) #sorts through cache_file data
# TypeError: string indices must be integers

我已经尝试了很多东西,但我觉得我错过了一件阻止它工作的小东西。

如果您还需要帮助调试此问题,请询问...

编辑:这是代码的要点,私人信息已编辑。 https://gist.github.com/Xioto/4b7979f5fef0f4d646b03555811229ac

这也是response.json。 https://gist.github.com/Xioto/00f05431e2e9a2cb6888728ea97ca101

您要求对data进行排序,这是一个看起来像这样的JSON:

data = {
"hours": [
{
"time": "2021-06-12T00:00:00+00:00",
"waveHeight": {
"dwd": 0.25,
"fcoo": 0.43,
"icon": 0.54,
"meteo": 0.44,
"noaa": 0.71,
"sg": 0.43
}
}
...  # many others
],
}

所以 Python 尝试对data进行排序,这是一个字典,所以它会获取键并将它们提供给你的 lambda。但:

>>> data.keys()
dict_keys(['hours'])

字典的所有键都由一个仅包含一个项目的列表组成,"hour".因此,字符串hours提供给您的 lambda,它试图获取其第"hours"个字符,但由于string indices must be integers而不起作用。

你在sorted上犯了两个错误:

  • 首先,您应该分配返回值,因为sorted没有就地
  • 其次,您的键 lambda 不正确,它的作用是检索要排序的键,因此对于"波元素"(具有时间和高度),因为您想按升序对它们进行排序,它应该返回波的time值。

这是您的问题的最小可重现示例(我曾经诊断过):

data = {
"hours": [
{
"time": "2021-06-12T00:00:00+00:00",
"waveHeight": {
"dwd": 0.25,
"fcoo": 0.43,
"icon": 0.54,
"meteo": 0.44,
"noaa": 0.71,
"sg": 0.43
}
}
],
}
sorted(data, key = lambda i: i['hours']) #sorts through cache_file data 
print([0])

这是正确的版本:

waves = sorted(
data["hours"],  # I'm sorting the list of wave data contained in the JSON
key=lambda wave: wave["time"]  # according to their respective "time" attribute
)
print(waves[0])

最新更新