beaconhill
beaconhill

Reputation: 451

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": "[email protected]", 
         "direction": "Southbound", 
         "station": "place-har"
     }, 
     "-bus": {
         "email_address": "[email protected]", 
         "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.

Upvotes: 1

Views: 5125

Answers (1)

gen_Eric
gen_Eric

Reputation: 227180

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 dicts into OrderedDicts 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)

Upvotes: 4

Related Questions