【问题标题】:Creating Nested Dictionary from CSV in Python [duplicate]在 Python 中从 CSV 创建嵌套字典 [重复]
【发布时间】:2023-03-20 01:18:01
【问题描述】:

我知道以前有人问过这个问题,但我不知道我的情况。

我想将 csv 文件中的玩家统计数据读入嵌套字典。预期的结果是这样的:

dictionary = {
  "player1": {
    "goals" : 5,
    "assists" : 7,
    "games played" : 50
  },
  "player2": {
    "goals" : 4,
    "assists" : 8,
    "games played" : 49
  },
  "player3": {
    "goals" : 6,
    "assists" : 10,
    "games played" : 53
  },
}

csv 文件如下所示:

Player  Goals  Assists  Games Played
player1 5      7        50
player2 4      8        49
player3 6      10       53

最后我希望能够通过调用来访问球员的统计数据,例如:

x = dictionary.get("player1")
print(x)

对 python 非常陌生,因此非常感谢任何有关如何实现这一点的帮助!

【问题讨论】:

标签: python


【解决方案1】:

考虑使用pandas 模块,而不是字典。它允许以其他 Python 数据结构难以实现的方式轻松访问列和行。

您可以将您的 CSV 文件放入 Pandas 中称为 dataframe 的文件中,然后访问某些值与您要查找的内容匹配的行,例如 player1

dataframe = pandas.read_csv("players.csv")
player_column = dataframe["Player"]
player1_row = dataframe.loc[player_column == "player1"]

.loc 定位玩家列 (Player) 中的值等于player1 的行。

More on Pandas here.

【讨论】:

    猜你喜欢
    • 2021-02-20
    • 2019-02-21
    • 1970-01-01
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    • 2016-02-27
    • 1970-01-01
    • 2019-05-22
    相关资源
    最近更新 更多