繁体   English   中英

KeyError:在Python中为0

[英]KeyError: 0 in Python

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

KeyError: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是什么,我需要选择数组中的第一个对象。

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

但是,您可以尝试使用json.loads (和json.load )的object_pairs_hook参数将这些dict转换为OrderedDict 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

暂无
暂无

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

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