1

I am trying to make a database of baseball stats and lineups. Is there a way to loop through a list of teams and use a string as an variable name?

For example: Extract team name

team_name = 'BOS'

Use BOS as variable name for object and append to list of objects

BOS = team_data()
teams.append(BOS)

Then when I index some stats, I can do the following to retrieve the lineup:

teams.BOS.lineup

I know in Matlab you can do the following and I was wondering if there is an equivalent in Python:

teams.(team_name).lineup

Currently I have it assigning the data to the same variable name each loop and appending to the list.

teams[0].team_name = 'BOS'
teams[1].team_name = 'NYY'

My only other thought is to have a switch case for team_name to assign to the team variable name.

2
  • 1
    for team_name in teams:? Commented Jul 16, 2017 at 14:51
  • The equivalent of your matlab example is getattr(teams, team_name).lineup . You can also setattr(teams, team_name, team_data()) Commented Jul 16, 2017 at 17:10

1 Answer 1

4

Use dictionary:

teams = {}

teams['BOS'] = team_data()   
teams['NYY'] = team_data() 

for key in teams:
    print(teams[key].team_name) # removed the quotes around "key"
Sign up to request clarification or add additional context in comments.

2 Comments

Do the team name strings have to be preset, or can it be done when I get the string of the team name?
They don't have to be preset. You can create keys dynamically.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.