Empty list purpose

In the function below:

def group_games_by_col(games, col_index):

Given a column index, creates a dictionary
where the keys are the values on that column
and each value is the list of all games with
the same value on that column.

games_per_col = {}
    for game in games:
        key = game[col_index]
        if not game[col_index] in games_per_col:
            games_per_col[key] = []    <-------  ??
        games_per_col[key].append(game)
    return games_per_col
  1. What is the meaning of the empty list here? games_per_col[key] = [] What does exactly the code do here?

  2. Would it be correct to write the following code to have the same result?
    games_per_col = {}
    for game in games:
    key = game[col_index]
    if game[col_index] in games_per_col:
    games_per_col[key].append(game)

    return games_per_col

If a key does not exist in the dictionary,

  • games_per_col[key] - Access the value for key in the dictionary will give an error KeyError.

To solve the KeyError, assigned initial value to key.
games_per_col[key] = [] initialised the key, value pair in the dictionary.

The code below is not the Pythonic way to do when you want to insert/append a dictionary value to a list for a missing key.

 if not game[col_index] in games_per_col:
            games_per_col[key] = []    
        games_per_col[key].append(game)

Use defaultdict. For missing keys, the dictionary will gives the default value. For default list value in defaultdict is an empty list [ ]. For default integer value in defaultdict is 0.

from collections import defaultdict
games_per_col = defaultdict(list)

Don’t need care if the key exists before or not.

games_per_col[key].append(game)

When a key is missing, defaultdict will return the default value indicated. In our case, the default value is an empty list [ ].

games_per_col[key].append(game) becomes [].append(game) behind the scenes.

1 Like