Home > Enterprise >  Python - List of lists - S&P500
Python - List of lists - S&P500

Time:05-26

I am new to python and am looking to analyze the S&P500 by sector. I have assigned symbols to all 11 sectors in the S&P with the first two looking like: Financials = ['AFL', 'AIG', .... 'ZION'] Energy = ['APA', 'BKR', ... 'SLB']

I then create a new list (of lists) which might look like: sectors_to_analyze = [Financials, Energy] or [Materials, ConsumerStaples]

My analysis is working perfectly, but I want to retrieve the names "Financials" and "Energy" to attach to the data produced and I cannot figure out how to do it other than make the name part of the list (Financials = ['Financials','AFL', 'AIG', .... 'ZION']

Can someone please point me in the right direction? Thank you.

CodePudding user response:

Perhaps you could use a dictionary

sectors = {
    'Financials':['AFL', ...],
    # rest of your lists
}

Then you can iterate over the whole dict and access both names and data associated with those names

for key, value in sectors.items():
    print(f'Sector name: {key}, List: {value}')

CodePudding user response:

I think you want to use a dictionary instead of a "list of lists" (also called a two dimensional list). You could then loop over the dictionary almost the same way. Here's some example code:

Financials = ['AFL', 'AIG', 'ZION']
Energy = ['APA', 'BKR', 'SLB']
sectors = {"Finacials": Financials, "Energy": Energy}

# in this loop, sector is the sector's name, and symbols is the sector's 
# list
for sector in sectors:
     symbols = sectors[sector]
     # ...
     # do some analysis
     # ...
  • Related