理解下面的一段代码

Understanding the following piece of code

以下程序用于将从 nba_api 获得的列表转换为数据帧,但无法理解它想要传达或正在执行的功能。 谁能帮我理解一下。

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())

让我们从卡住的地方开始分解:

# 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)

其实这段代码就是将list_dict中的字典合并成一个单独的字典,构造一个DataFrame。实际上它没有用,因为 pandas 可以直接从字典列表中创建一个 DataFrame :

dict_1 = {'A': 22, 'B': 42}
dict_2 = {'A': 28, 'B': 1}

list_dict = [dict_1, dict_2]
df = pd.DataFrame(list_dict)