-2

I have a for loop that is going through a dictionary with a lot of nested dictionaries. When the loop gets to an entry that doesn't have the key I am looking for it stops. How do I make it keep going through all the rest of the data?

In my code the loop goes through the games fine. When I try to get all the game['odds'] the loop stops if one game doesn't have an odds key which ends up giving me a key error and only printing out the first four games.

    results = requests.request("GET", url, headers=headers).json()
    games = results['results']
    for game in games:
        spread = game['odds']
        for line in spread:
            points = line['spread']['current']['home']
            print(points)
Ryan Thomas
  • 488
  • 4
  • 14
  • 1
    well, the answer of your question - why, is in your post - "one game doesn't have an odds key which ends up giving me a key error" – buran Mar 06 '21 at 19:36
  • Does this answer your question? [Best way to handle a keyerror in a dict](https://stackoverflow.com/questions/36597869/best-way-to-handle-a-keyerror-in-a-dict) – buran Mar 06 '21 at 19:37
  • Also https://stackoverflow.com/questions/10116518/im-getting-key-error-in-python – buran Mar 06 '21 at 19:38

3 Answers3

1

Replace spread = game['odds'] with spread = game.get('odds',[]) so that spread gets an empty list when there is no 'odds' key and the rest of the code will behave correctly.

Alain T.
  • 40,517
  • 4
  • 31
  • 51
0

I'm going to assume that it stops because of a KeyError Here, you have two choices to overcome it.

dict().get()

d = {}
d.get('foo') #Returns None

The .get() method is handy because if the specified key doesn't exist, then it will simply return None. Use where you don't want to deal with errors raining from the sky.

try except

Slightly more complex.

try:
    raise ValueError('ya goofed m8')
except ValueError:
    print('How the tables have turned...')

This will listen for an error and then execute some code if that error happens try is the code you want to listen for an error in. except is the code for the error.

coderman1234
  • 210
  • 3
  • 12
-1

Try doing this:

results = requests.request("GET", url, headers=headers).json()
    games = results['results']
    for game in games:
        if(game['odds']):
            spread = game['odds']
            for line in spread:
                points = line['spread']['current']['home']
                print(points)
Cute Panda
  • 1,468
  • 1
  • 6
  • 11