CajunTechie
CajunTechie

Reputation: 605

How can I get the 'Last' value from this dictionary?

I'm working with an API that is sending my Python program the following data back:

{"success":"true","message":"","result":   
 [{"Last":"0.00000000","Bid":"42258.06451613","Ask":"100000000.0"}]}

I'm pretty new to working with JSON in Python but thought I could do something like:

data = json.load(urllib2.urlopen("apicall"))
last = data["success"]["message"]["result"]["Last"]

but apparently I need to use integers instead. So when I do

last = data[0][0][0][0]

I'm told that's an invalid key. So my question is: what is the proper way to get the value of the 'Last' key in this example?

Upvotes: 1

Views: 2153

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121804

The proper way is to address the outer dictionary, then index the list, then get the 'Last' key:

last = data['result'][0]['Last']

Demo:

>>> from pprint import pprint
>>> data = {"success":"true","message":"","result":   
...  [{"Last":"0.00000000","Bid":"42258.06451613","Ask":"100000000.0"}]}
>>> pprint(data)
{'message': '',
 'result': [{'Ask': '100000000.0',
             'Bid': '42258.06451613',
             'Last': '0.00000000'}],
 'success': 'true'}
>>> data['result']
[{'Ask': '100000000.0', 'Bid': '42258.06451613', 'Last': '0.00000000'}]
>>> data['result'][0]
{'Ask': '100000000.0', 'Bid': '42258.06451613', 'Last': '0.00000000'}
>>> data['result'][0]['Last']
'0.00000000'

Your first attempt tried to address all the keys in the top-level dictionary, which would have failed because data['success'] is a string, and strings cannot be indexed by ['message'].

Your second attempt failed because the top-level object is a dictionary, not a sequence, and there is no 0 key in it.

Upvotes: 3

Related Questions