Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to loop multiple tickers into a function and I can print successfully the results however I cannot store them, only the last element is outputted. The loop seems overwrites the values generated earlier, can you please advise?

import yfinance as yf

y = ['SBUX', 'ICE']
b = {}

for x in y:
    ticker = yf.Ticker(x)
    d = ticker.get_info()
    for k, v in d.items():
        if k == 'zip' or k == 'sector' or k == 'symbol':
            b[k] = d[k]
    print(b)

result from the code:

{'zip': '98134', 'sector': 'Consumer Cyclical', 'symbol': 'SBUX'}
{'zip': '30328', 'sector': 'Financial Services', 'symbol': 'ICE'}

result if b is printed outside the code:

{'zip': '30328', 'sector': 'Financial Services', 'symbol': 'ICE'}

I would like to be able to print the 2 lines outside the code


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

You can append them to a dataframe:

import yfinance as yf
import pandas as pd

new_df = pd.DataFrame()
y = ['SBUX', 'ICE']
b = {}

for x in y:
    ticker = yf.Ticker(x)
    d = ticker.get_info()
    for k, v in d.items():
        if k == 'zip' or k == 'sector' or k == 'symbol':
            b[k] = d[k]
    new_df = new_df.append(b, ignore_index=True)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...