【问题标题】:KeyError: 0 in Python关键错误:Python 中的 0
【发布时间】:2017-09-10 19:33:18
【问题描述】:

我正在尝试获取此 JSON 中返回的第一个对象的 directionstation 的值,但出现以下错误

密钥错误:0

这是我的代码:

print(json.dumps(savedrequest, indent=4))
savedstation = savedrequest[0]['station']
saveddirection = savedrequest[0]['direction']

这就是它在打印中返回的内容:

{
     "-bas": {
         "email_address": "dd3@gmail.com", 
         "direction": "Southbound", 
         "station": "place-har"
     }, 
     "-bus": {
         "email_address": "dd4@gmail.com", 
         "direction": "Southbound", 
         "station": "place-su"
     }
 }

我不知道-bas-bus返回时会是什么,我需要选择数组中的第一个对象。

【问题讨论】:

  • savedrequest 不是数组,它没有键 0。您需要使用'-bas'(或'-bus')。
  • 在那个数组中,有没有办法选择第一个对象并从directionstation 键中获取值?
  • 你为什么要访问密钥0
  • 没有数组。您有一个 JSON object,它被转换为 python dict。 python中的字典本质上是无序的,所以没有“第一个”元素的概念
  • 不是数组,是字典。字典没有顺序,所以你不能使用[0]、[1]等来访问它们。你只能通过字典中的键来访问它们。没有其他办法。

标签: python json keyerror


【解决方案1】:

您的 JSON 被解码为“对象”(在 python 中称为dict),它不是数组。因此,它没有特定的“顺序”。您认为的“第一个”元素实际上可能不会以这种方式存储。不能保证每次都是同一个对象。

但是,您可以尝试使用json.loads(和json.load)的object_pairs_hook 参数将这些dicts 转换为OrderedDicts。 OrderedDict 类似于 dict,但它会记住向其中插入的 order 元素。

import json
from collections import OrderedDict

savedrequest = json.loads(data, object_pairs_hook=OrderedDict)

# Then you can get the "first" value as `OrderedDict` remembers order
#firstKey = next(iter(savedrequest))
first = next(iter(savedrequest.values()))

savedstation = first['station']
saveddirection = first['direction']

(此答案感谢https://stackoverflow.com/a/6921760https://stackoverflow.com/a/21067850

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    • 2018-09-20
    • 1970-01-01
    • 1970-01-01
    • 2015-09-09
    • 1970-01-01
    相关资源
    最近更新 更多