如何在列印陳述句中訪問物件“c”?
{'symbol': 'BTCUSD', 'totalResults': 1, 'results': [{'o': 41002.26, 'h': 43361, 'l': 40875.51, 'c': 42364.13, 'v': 59454.94294, 't': 1647993599999}]}
總體代碼(API 密鑰已洗掉但不是問題):
command = ""
while(command != "q"):
command = input("Choose [c] for current price, [p] for previous days price, and [q] to quit.")
if(command == "c"):
coin = input("Enter currency pair: ")
crypto_data = (requests.get(f'https://api.finage.co.uk/last/crypto/{coin}?apikey=API_KEY')).json()
print(f"The current price of {coin} is {crypto_data['price']}")
if(command == "p"):
coin = input("Enter currency pair: ")
crypto_data = (requests.get(f'https://api.finage.co.uk/agg/crypto/prev-close/{coin}?apikey=API_KEY')).json()
*print(f"The previous price of {coin} is {crypto_data['results']['c']}")*
- 作為我得到問題的地方,我得到了各種代碼,主要是我不能呼叫一個字串,它必須是一個切片或整數
我也嘗試過一個范圍宣告,但它也帶來了一個錯誤
蒂亞!
uj5u.com熱心網友回復:
如果它們首先在字典中,然后是陣列,然后再次在字典中,則方法相同:
crypto_data = {'symbol': 'BTCUSD', 'totalResults': 1, 'results': [{'o': 41002.26, 'h': 43361, 'l': 40875.51, 'c': 42364.13, 'v': 59454.94294, 't': 1647993599999}]}
print(crypto_data["results"][0]["c"])
這是因為:
# crypto_data is a dictionary, so you can access items by their key, i.e.
crypto_data["results"]
# which returns an array: [{'o': 41002.26, 'h': 43361, 'l': 40875.51, 'c': 42364.13, 'v': 59454.94294, 't': 1647993599999}]
# so then access items in the array by their index, i.e.
crypto_data["results"][0]
# which returns a dictionary: {'o': 41002.26, 'h': 43361, 'l': 40875.51, 'c': 42364.13, 'v': 59454.94294, 't': 1647993599999}
# so then access items in the dictionary by their key again, i.e.
crypto_data["results"][0]["c"]
# which returns an integer: 42364.13
uj5u.com熱心網友回復:
如果
myDict = {'symbol': 'BTCUSD', 'totalResults': 1, 'results': [{'o': 41002.26, 'h': 43361, 'l': 40875.51, 'c': 42364.13, 'v': 59454.94294, 't': 1647993599999}]}
然后myDict["results"][0]["c"]將回傳 42364.1
uj5u.com熱心網友回復:
這是因為盡管您知道字典在串列中,但您仍試圖訪問字典,就好像它不在串列中一樣。
這非常重要results:此 API 可以在串列中回傳多個字典- 請參閱totalResults鍵。
獲得結果的最佳方法是執行for...range回圈:
for idx in range(crypto_data['totalResults']): print(crypto_data['results'][idx])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/447779.html
下一篇:如何一次添加多個嵌套字典?
