Search code examples
pythonpandaslistdataframenba-api

Understanding the following piece of code


The following program is used to convert to a list obtained from nba_api to a dataframe but unable to understand the function as to what it wants to convey or is perfroming. Can someone help me understand it.

from nba_api.stats.static import teams
import pandas as pd

nba_teams = teams.get_teams()
print(nba_teams[:5])

def one_dict(list_dict):  #Creating function one_dict

#could'nt understand it further than this.

    keys = list_dict[0].keys()
    out_dict = {key:[] for key in keys }
    for dict_ in list_dict:
        for key, value in dict_.items():
            out_dict[key].append(value)
    return out_dict

dict_nba_team = one_dict(nba_teams)

df_team = pd.DataFrame(dict_nba_team)
print(df_team.head())

Solution

  • Let's break it down from where you're stuck :

    # we get the keys from the first dict passed to the function
    keys = list_dict[0].keys()
    
    # we initialize a new dict where the definition for each key is an empty list
    out_dict = {key:[] for key in keys }
    
    for dict_ in list_dict:
            # for each key in dict_ you append the value to the the list associated to this key in the out_dict
            for key, value in dict_.items():
                out_dict[key].append(value)
    

    In fact, this piece of code is merging the dictionaries in list_dict into a single one to construct a DataFrame. Actually it's not useful because pandas can create a DataFrame directly from the list of dictionaries :

    dict_1 = {'A': 22, 'B': 42}
    dict_2 = {'A': 28, 'B': 1}
    
    list_dict = [dict_1, dict_2]
    df = pd.DataFrame(list_dict)