0

Suppose we have the following dataframe

import yfinance as yf 
import numpy as np
import numpy_financial as npf
import matplotlib.pyplot as plt
from os import system
import sys, time
import pandas as pd
import requests


import ssl

ssl._create_default_https_context = ssl._create_unverified_context

url_link = 'https://finance.yahoo.com/quote/TSLA/analysis?p=TSLA'
r = requests.get(url_link,headers ={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'})

data = pd.read_html(r.text)
data = data[0]
data = data[data['Earnings Estimate'] == 'Avg. Estimate']

data.plot(kind='bar')

data = yf.Ticker("TSLA")

The following operations are easy

for key, value in data.info.items():
    print(f"{key} : {value}")
    print("")

This prints out each of dictionary entries line by line, with a space in between.

keys_list = list(data.info.keys())
values_list = list(data.info.values())

These operations separate the keys and values of the dictionary into their own distinct lists. This makes it possible to do one of the following two operations...

for key in data.info.keys():
    print(str(keys_list.index(key)) + ". " + str( key ))  

for value in data.info.values():
    print(str(values_list.index(value)) + ". " + str( value ))

either of these are fine, and what they do is print out an index number, plus the sring value of the item in the list.

But what I would like to is print out an index number, then the key, and then the value,

so that the output format looks something like

1. key: value
2. key: value
3: key: value

I've tried creating a variable to represent an integer alongside the key/values in a for loop, but I get the following error message

valueError: too many values to unpack (expected 3, got 2)

So really I'm not sure what else I should try to wrangle the output to the desired format.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241

1 Answers1

0

Use items() to get the keys and values together. Use enumerate() to return an index along with the values form an iterator.

for i, (key, value) in enumerate(data.info.items(), 1):
    print(f"{i}. {key}: {value}")

Notice that you have to group key and value in a tuple, because that's what items() returns for each element.

Barmar
  • 741,623
  • 53
  • 500
  • 612