Caiotru
Caiotru

Reputation: 325

Pandas/Python how to store store looped values

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

Upvotes: 0

Views: 38

Answers (1)

gtomer
gtomer

Reputation: 6574

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)

Upvotes: 1

Related Questions