简体   繁体   中英

KeyError: 0 in Python

I'm trying to get the values of the first object's direction and station returned in this JSON, but I'm getting the following error

KeyError: 0

Here's my code:

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

And this is what it's returning in the print:

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

I don't know what -bas or -bus is going to be when it gets returned, I need to select the first object in the array.

Your JSON was decoded into an "object" (called a dict in python), it's not an array. As such, it has no particular "order". What you think is the "first" element may not actually be stored that way. There's no guarantee that the same object will be first each time.

What you could try, however, is to convert these dict s into OrderedDict s by using the object_pairs_hook parameter of json.loads (and json.load ). An OrderedDict is like a dict , but it remembers the that order elements were inserted into it.

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']

(This answer is thanks to https://stackoverflow.com/a/6921760 and https://stackoverflow.com/a/21067850 )

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