Geraldo Moura
Geraldo Moura

Reputation: 59

For loops output all the same value

So I have a json list and use two input request.args.get('sport') and request.args.get('team') to find those values in my list. If the value is found I want to output more info on the team and sport.

This is what I tried to do:

for a_team in scores_list['scores']:
    if a_team['sport'].lower() == request.args.get('sport').lower() \
            and a_team['team'].lower() == request.args.get('team').lower():
        teams_list = []
        for a_team['team'] in scores_list['scores']:
            teams_list.append("{} ({}) ({}) {} ({}) - ({}) {}".format(a_team['full_name'], a_team['date'],
                                                                      a_team['sport'], a_team['home_name'],
                                                                      a_team['home_score'], a_team['away_score'],
                                                                      a_team['away_name']))

The problem is that this way is outputting the same set of values over. I want to output all different games with the the team from request.args.get('team'). I am new to python and I have searched everyone but couldn't find an answer.

Below is a sample of my json file:

 {
  "scores": [
    {
      "sport": "football",
      "team": "packers",
      "full_name": "Green Bay Packers",
      "week": "15-2020",
      "boxscore": "202012190gnb",
      "away_name": "Carolina Panthers",
      "away_abbr": "car",
      "away_score": 16,
      "home_name": "Green Bay Packers",
      "home_abbr": "gnb",
      "home_score": 24,
      "winning_name": "Green Bay Packers",
      "winning_abbr": "gnb",
      "losing_name": "Carolina Panthers",
      "losing_abbr": "car"
    },
    {
      "sport": "football",
      "team": "packers",
      "full_name": "Green Bay Packers",
      "week": "19-2020",
      "boxscore": "202101160gnb",
      "away_name": "Los Angeles Rams",
      "away_abbr": "ram",
      "away_score": 18,
      "home_name": "Green Bay Packers",
      "home_abbr": "gnb",
      "home_score": 32,
      "winning_name": "Green Bay Packers",
      "winning_abbr": "gnb",
      "losing_name": "Los Angeles Rams",
      "losing_abbr": "ram"
    },
    {
      "sport": "football",
      "team": "packers",
      "full_name": "Green Bay Packers",
      "week": "20-2020",
      "boxscore": "202101240gnb",
      "away_name": "Tampa Bay Buccaneers",
      "away_abbr": "tam",
      "away_score": 31,
      "home_name": "Green Bay Packers",
      "home_abbr": "gnb",
      "home_score": 26,
      "winning_name": "Tampa Bay Buccaneers",
      "winning_abbr": "tam",
      "losing_name": "Green Bay Packers",
      "losing_abbr": "gnb"
    },
    {
      "sport": "football",
      "team": "chiefs",
      "full_name": "Kansas City Chiefs",
      "week": "16-2020",
      "boxscore": "202012270kan",
      "away_name": "Atlanta Falcons",
      "away_abbr": "atl",
      "away_score": 14,
      "home_name": "Kansas City Chiefs",
      "home_abbr": "kan",
      "home_score": 17,
      "winning_name": "Kansas City Chiefs",
      "winning_abbr": "kan",
      "losing_name": "Atlanta Falcons",
      "losing_abbr": "atl"
    },
    {
      "sport": "football",
      "team": "chiefs",
      "full_name": "Kansas City Chiefs",
      "week": "17-2020",
      "boxscore": "202101030kan",
      "away_name": "Los Angeles Chargers",
      "away_abbr": "sdg",
      "away_score": 38,
      "home_name": "Kansas City Chiefs",
      "home_abbr": "kan",
      "home_score": 21,
      "winning_name": "Los Angeles Chargers",
      "winning_abbr": "sdg",
      "losing_name": "Kansas City Chiefs",
      "losing_abbr": "kan"
    },
    {
      "sport": "football",
      "team": "chiefs",
      "full_name": "Kansas City Chiefs",
      "week": "19-2020",
      "boxscore": "202101170kan",
      "away_name": "Cleveland Browns",
      "away_abbr": "cle",
      "away_score": 17,
      "home_name": "Kansas City Chiefs",
      "home_abbr": "kan",
      "home_score": 22,
      "winning_name": "Kansas City Chiefs",
      "winning_abbr": "kan",
      "losing_name": "Cleveland Browns",
      "losing_abbr": "cle"
    },
    {
      "sport": "football",
      "team": "chiefs",
      "full_name": "Kansas City Chiefs",
      "week": "19-2020",
      "boxscore": "202101240kan",
      "away_name": "Buffalo Bills",
      "away_abbr": "buf",
      "away_score": 24,
      "home_name": "Kansas City Chiefs",
      "home_abbr": "kan",
      "home_score": 38,
      "winning_name": "Kansas City Chiefs",
      "winning_abbr": "kan",
      "losing_name": "Buffalo Bills",
      "losing_abbr": "buf"
    },
    {
      "sport": "football",
      "team": "buccaneers",
      "full_name": "Tampa Bay Buccaneers",
      "week": "21-2020",
      "boxscore": "202102070tam",
      "away_name": "Kansas City Chiefs",
      "away_abbr": "kan",
      "away_score": 9,
      "home_name": "Tampa Bay Buccaneers",
      "home_abbr": "tam",
      "home_score": 31,
      "winning_name": "Tampa Bay Buccaneers",
      "winning_abbr": "tam",
      "losing_name": "Kansas City Chiefs",
      "losing_abbr": "kan"
    },
    {
      "sport": "baseball",
      "team": "giants",
      "full_name": "San Francisco Giants",
      "date": "7-23-2020",
      "boxscore": "LAN/LAN202007230",
      "away_name": "San Francisco Giants",
      "away_abbr": "SFG",
      "away_score": 1,
      "home_name": "Los Angeles Dodgers",
      "home_abbr": "LAD",
      "home_score": 8,
      "winning_name": "Los Angeles Dodgers",
      "winning_abbr": "LAD",
      "losing_name": "San Francisco Giants",
      "losing_abbr": "SFG"
    },
    {
      "sport": "baseball",
      "team": "giants",
      "full_name": "San Francisco Giants",
      "date": "7-24-2020",
      "boxscore": "LAN/LAN202007240",
      "away_name": "San Francisco Giants",
      "away_abbr": "SFG",
      "away_score": 1,
      "home_name": "Los Angeles Dodgers",
      "home_abbr": "LAD",
      "home_score": 9,
      "winning_name": "Los Angeles Dodgers",
      "winning_abbr": "LAD",
      "losing_name": "San Francisco Giants",
      "losing_abbr": "SFG"
    },
    {
      "sport": "baseball",
      "team": "giants",
      "full_name": "San Francisco Giants",
      "date": "7-25-2020",
      "boxscore": "LAN/LAN202007250",
      "away_name": "San Francisco Giants",
      "away_abbr": "SFG",
      "away_score": 5,
      "home_name": "Los Angeles Dodgers",
      "home_abbr": "LAD",
      "home_score": 4,
      "winning_name": "San Francisco Giants",
      "winning_abbr": "SFG",
      "losing_name": "Los Angeles Dodgers",
      "losing_abbr": "LAD"
    },
    {
      "sport": "baseball",
      "team": "giants",
      "full_name": "San Francisco Giants",
      "date": "8-5-2020",
      "boxscore": "COL/COL202008050",
      "away_name": "San Francisco Giants",
      "away_abbr": "SFG",
      "away_score": 4,
      "home_name": "Colorado Rockies",
      "home_abbr": "COL",
      "home_score": 3,
      "winning_name": "San Francisco Giants",
      "winning_abbr": "SFG",
      "losing_name": "Colorado Rockies",
      "losing_abbr": "COL"
    },
    {
      "sport": "baseball",
      "team": "giants",
      "full_name": "San Francisco Giants",
      "date": "8-6-2020",
      "boxscore": "COL/COL202008060",
      "away_name": "San Francisco Giants",
      "away_abbr": "SFG",
      "away_score": 4,
      "home_name": "Colorado Rockies",
      "home_abbr": "COL",
      "home_score": 6,
      "winning_name": "Colorado Rockies",
      "winning_abbr": "COL",
      "losing_name": "San Francisco Giants",
      "losing_abbr": "SFG"
    },
    {
      "sport": "baseball",
      "team": "rays",
      "full_name": "Tampa Bay Rays",
      "date": "10-27-2020",
      "boxscore": "LAN/LAN202010270",
      "away_name": "Tampa Bay Rays",
      "away_abbr": "TBR",
      "away_score": 1,
      "home_name": "Los Angeles Dodgers",
      "home_abbr": "LAD",
      "home_score": 3,
      "winning_name": "Los Angeles Dodgers",
      "winning_abbr": "LAD",
      "losing_name": "Tampa Bay Rays",
      "losing_abbr": "TBR"
    }
  ]
}

Upvotes: 1

Views: 87

Answers (4)

madbird
madbird

Reputation: 1379

  1. Probably you shouldn't clear the list of teams on every iteration:
for i in range(3):
    # Here you'll bind a new empty 
    # list to the variable `result`
    # each time this line executed
    results = [i]
print(results)
# [2]

Instead, please create a list outside of the loop, and append new values during iteration:

results = []  # List created before entering the loop
for i in seq:
    results.append(i)  # And new values appended to the same list
print(results)
# [0, 1, 2]

  1. Do you clearly understand what's happening, when you use a dict lookup as a loop variable?
d = {'a': 1}
for d['a'] in range(10):
    pass
print(d)
# {'a': 9}

This literally means:

  • get the next item from the iterable (sequence)
  • and put this item to dict d by key 'a'

To make code more predictable, please define the new variable in you need in for loop.

d = {'a': 0}
for a in range(3):
    d['a'] = d['a'] + a
print(d)
# {'a': 3}

Upvotes: 1

JonSG
JonSG

Reputation: 13067

My answer will include only two entries in scores_list representing your json datafile, but the code should get you going again. I'm going to use a list comprehension (mostly because I like them). Technically the method details of game_info() could be handled in the comprehension, but I don't think that really adds clarity.

import json # for printing in demo

## -----------------------
# this just makes our comprehension easier to follow later in the code.
## -----------------------
def game_info(game):
    return "{} ({}) ({}) {} ({}) - ({}) {}".format(
        game['full_name'],
        game['date'],
        game['sport'],
        game['home_name'],
        game['home_score'],
        game['away_score'],
        game['away_name']
    )
## -----------------------

scores_list = {
  "scores": [
    {
      "sport": "football",
      "team": "packers",
      "full_name": "Green Bay Packers",
      "week": "15-2020",
      "boxscore": "202012190gnb",
      "away_name": "Carolina Panthers",
      "away_abbr": "car",
      "away_score": 16,
      "home_name": "Green Bay Packers",
      "home_abbr": "gnb",
      "home_score": 24,
      "winning_name": "Green Bay Packers",
      "winning_abbr": "gnb",
      "losing_name": "Carolina Panthers",
      "losing_abbr": "car"
    },
    ## rows removed for clarity....
    {
      "sport": "baseball",
      "team": "rays",
      "full_name": "Tampa Bay Rays",
      "date": "10-27-2020",
      "boxscore": "LAN/LAN202010270",
      "away_name": "Tampa Bay Rays",
      "away_abbr": "TBR",
      "away_score": 1,
      "home_name": "Los Angeles Dodgers",
      "home_abbr": "LAD",
      "home_score": 3,
      "winning_name": "Los Angeles Dodgers",
      "winning_abbr": "LAD",
      "losing_name": "Tampa Bay Rays",
      "losing_abbr": "TBR"
    }
  ]
}

#requested_sport = request.args.get('sport').lower()
requested_sport = "baseball"

#requested_team = request.args.get('team').lower()
requested_team = "rays"

## -----------------------
# find all the games where we have a match on both sport and team name.
## -----------------------
interesting_games = [
    game_info(game) for game in scores_list['scores']
    if game["sport"] == requested_sport and game["team"] == requested_team
]
## -----------------------

print(json.dumps(interesting_games, indent=2))

This should give you:

[
  "Tampa Bay Rays (10-27-2020) (baseball) Los Angeles Dodgers (3) - (1) Tampa Bay Rays"
]

If you did not want to use the method call then the comprehension might be more like:

interesting_games = [
    "{} ({}) ({}) {} ({}) - ({}) {}".format(
        game['full_name'],
        game['date'],
        game['sport'],
        game['home_name'],
        game['home_score'],
        game['away_score'],
        game['away_name']
    )
    for game in scores_list['scores']
    if game["sport"] == requested_sport and game["team"] == requested_team
]

Upvotes: 1

RufusVS
RufusVS

Reputation: 4127

Are you looking for this simpler solution?

teams_list = []
for a_team in scores_list['scores']:
    if a_team['sport'].lower() == request.args.get('sport').lower() \
            and a_team['team'].lower() == request.args.get('team').lower():
        teams_list.append("{} ({}) ({}) {} ({}) - ({}) {}".format(a_team['full_name'], a_team['date'],
                                                                  a_team['sport'], a_team['home_name'],
                                                                  a_team['home_score'], a_team['away_score'],
                                                                  a_team['away_name']))

Upvotes: 0

danr
danr

Reputation: 2415

        for team in scores_list['scores']:
            teams_list.append("{} ({}) ({}) {} ({}) - ({}) {}".format(team['full_name'], team['date'],
                                                                      team['sport'], team['home_name'],
                                                                      team['home_score'], team['away_score'],
                                                                      team['away_name']))

You're iterating over scores_list['scores'] at two locations in your source code:

for a_team in scores_list['scores']:
            # ^^^^^^^^^^^^^^^^^^^^^ here
    if a_team['sport'].lower() == request.args.get('sport').lower() \
            and a_team['team'].lower() == request.args.get('team').lower():
        teams_list = []
        for a_team['team'] in scores_list['scores']:
                            # ^^^^^^^^^^^^^^^^^^^^^ and here
            teams_list.append("{} ({}) ({}) {} ({}) - ({}) {}".format(a_team['full_name'], a_team['date'],
                                                                      a_team['sport'], a_team['home_name'],
                                                                      a_team['home_score'], a_team['away_score'],
                                                                      a_team['away_name']))

This is probably not what you want. When the if is true you already have an a_team in your hand you're interested in and you can just use it:

for a_team in scores_list['scores']:
    if a_team['sport'].lower() == request.args.get('sport').lower() \
            and a_team['team'].lower() == request.args.get('team').lower():
        teams_list = []
        teams_list.append("{} ({}) ({}) {} ({}) - ({}) {}".format(a_team['full_name'], a_team['date'],
                                                                  a_team['sport'], a_team['home_name'],
                                                                  a_team['home_score'], a_team['away_score'],
                                                                  a_team['away_name']))

Now you just need to figure out where you want to put teams_list = []. Probably before the for-loop starts.

Upvotes: 0

Related Questions