所以我試圖從包含大量詞典的串列中提取資料。特別是來自第一個字典的鍵:值對。如果可能,最終目標是將“符號”保存到變數,將“AAPL”保存到變數。這是我迄今為止提取整個串列的代碼:
from urllib.request import urlopen
import json
with urlopen("https://financialmodelingprep.com/api/v3/ratios/AAPL?apikey=MYAPIKEY") as response:
source = response.read()
data = json.loads(source)
data2 = json.dumps(data, indent=4)
print(data2)
上面的代碼列印以下內容(實際輸出的較小版本):
[
{
"symbol": "AAPL",
"date": "2021-09-25",
"period": "FY",
"currentRatio": 1.0745531195957954,
"quickRatio": 0.9096596297447422,
"cashRatio": 0.2784485300563432
},
{
"symbol": "AAPL",
"date": "2020-09-26",
"period": "FY",
"currentRatio": 1.3636044481554577,
"quickRatio": 1.2181949294064065,
"cashRatio": 0.36071049035979963
},
{
"symbol": "AAPL",
"date": "2019-09-28",
"period": "FY",
"currentRatio": 1.540125617208044,
"quickRatio": 1.3844473032028604,
"cashRatio": 0.46202160464632325
}
]
每本字典代表公司的不同年份。
如果我想提取第一個鍵:值對,我該如何實作?
我試過使用,[d['symbol'] for d in data2]但我TypeError: string indices must be integers
也試過使用切片來切割它,[d[0:1] for d in data2]但它回傳單個字符,如['[', '\n', ' ', ' ', ' ', ' ', '{', '\n', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '"', 's', 'y', 'm', 'b', 'o', 'l'
我一直在絞盡腦汁試圖得到這個,但不知道還能嘗試什么。謝謝。
uj5u.com熱心網友回復:
data2 是一個字串,這就是切片它回傳單個字符的原因。
要訪問串列中的第一個字典,請使用data[0]。
要訪問鍵在字典中,使用data[0]['symbol'],data[0]['date']等等。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/396279.html
上一篇:我有一個python串列,使用map函式省略了串列的第一個零
下一篇:列出每行帶有-v符號的檔案名
