簡體   English   中英

Python 字典,其中包含代碼列表中的鍵和 yfinance 中的值

[英]Python dictionary with keys from list of tickers and values from yfinance

您如何創建一個字典,其中鍵是列表中的代碼,值來自 yfinance(最近 7 天的股票價格)? 我嘗試了下面的代碼,但它沒有達到我所需要的。 它只為每個鍵添加一個值,而不是我想在這種情況下將 7 個股票價格添加到每個鍵。

list1 = tickers
list2 = []

for i in tickers:
    list2.extend(yf.Ticker(i).history(period='7d')['Close'])

dct = {}
for i, j in zip(list1, list2):
    try:
        dct.setdefault(i, []).append(j)
        
    except:
        print("The ticker {i} is causing an error")

您只需在第一個 for 循環中將它們添加到字典中:

for i in tickers:
.....
    dct[i] = list2

這將為列表中的每個鍵存儲 7 個值的列表

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM