0

I have a class where I assign a rating to each instance.

class Team:

def __init__(self, rating):
    "Initialize team with rating"
    self.rating = rating

I would like to be able to loop over a list of ratings, and create an instance for each rating, so if I have a list of ratings and team names, something like this:

scores = [10, 11, 12, 13]
teams = ['tm0', 'tm1', 'tm2', 'tm3']

for t, s in zip(teams, scores):
    t = Team(s)

tm2.rating    # returns 12

The above is not defining an instance of Team like I want it to.

I am new to Python so suspect there is an easy fix, or a more Pythonic way of doing this.

1

2 Answers 2

3

You appear to want a dict that maps each team name to an instance of Team.

scores = [10, 11, 12, 13]
team_names = ['tm0', 'tm1', 'tm2', 'tm3']
teams = {t: Team(s) for t, s in zip(team_names, scores)}

assert teams['tm0'].rating == 10
Sign up to request clarification or add additional context in comments.

2 Comments

z2 isn't really necessary, unless you need to save a reference to the object before assigning something else to the key with something like teams['tm2'] = Team(15).
Sorry, I just deleted the comment you replied to as I thought your edit (which I missed) resolved my question.
0

You can achieve what you want here with exec:

for t,s in zip(teams, scores):
    exec(f"{t} = Team({s})")

2 Comments

Can I ask why this is being downvoted? It works perfectly for me - is it because it is un-Pythonic in some way?
Generally speaking I would avoid using exec, as it executes an arbitrary command, which could have unexpected consequences.

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.