Home > OS >  Create dictionary with tickers as keys and values as stock prices
Create dictionary with tickers as keys and values as stock prices

Time:01-26

Is there a better way to achieve what the code below does? The list 'tickers' is a combination of stock tickers (e.g. AAPL, IBM)

list1 = tickers
list2 = []
dct = {}
count = 0

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

CodePudding user response:

Since len(yf.Ticker(i).history(period='7d')['Close'])==7, it seems redundant to extend a list and then slice off the items appended to the list. So instead of the convoluted loop, use a dict comprehension:

dct = {i: yf.Ticker(i).history(period='7d')['Close'] for i in tickers}

As an explicit loop:

dct = {}
for i in tickers:
    dct[i] = yf.Ticker(i).history(period='7d')['Close']
  •  Tags:  
  • Related