I have the following models:
class Fixture(models.Model):
id = models.AutoField(primary_key=True)
home_team = models.ForeignKey(Player, related_name="home")
away_team = models.ForeignKey(Player, related_name="away")
game_week = models.PositiveSmallIntegerField(max_length=2, default=0)
What I want to do i开发者_StackOverflow中文版s create a multi-dimensional list that groups all of my fixture objects by the 'game_week' property. For example:
fixtures[0] = [<FixtureObject 1>, <FixtureObject 2>]
fixtures[1] = [<FixtureObject 3>, <FixtureObject 4>]
fixtures[2] = [<FixtureObject 5>]
fixtures[3] = [<FixtureObject 6>]
Where the fixture list indexes are the different game weeks. What is the easiest, most pythonic way to do this?
Easiest way to do it is to use a dictionary:
fixtures = Fixture.objects.all()
fixture_dict = {}
for fixture in fixtures:
fixture_dict.setdefault(fixture.game_week, []).append(fixture)
精彩评论