简体   繁体   中英

What m i doing wrong in this code i have been stuck at

I'm trying to make a request and parse the current btc price..

my code

import requests
import json



r = requests.get('https://blockchain.info/ticker')

k = r.text


Rate = json.loads(k)


print(Rate["last"])

and the output is

Traceback (most recent call last):
  File "wifi2.py", line 14, in <module>
    print(Rate["last"])
KeyError: 'last'

how can i fix it? thanks

This is a sample entry from the URL you provided:

"USD" : {"15m" : 11237.41, "last" : 11237.41, "buy" : 11237.41, "sell" : 11237.41, "symbol" : "$"}

They Key is the shorthand for the currency, and it's value is another dictionary, such that:

'USD' -> {..., "last": 11237.41, ...}

To get the value of the last key of the inner dictionary, you need to do for example:

print(Rate["USD"]["last"])

This returns the dictionary associated with the first key, then the value associated with the last key of the inner dictionary.

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