python - 从 Python 中的多个列表创建复杂的嵌套字典

标签 python python-3.x dictionary

我正在努力创建一个包含以下数据的嵌套字典:

Team,       Group,  ID,  Score,  Difficulty
OneTeam,    A,      0,   0.25,   4
TwoTeam,    A,      1,   1,      10
ThreeTeam,  A,      2,   0.64,   5
FourTeam,   A,      3,   0.93,   6
FiveTeam,   B,      4,   0.5,    7
SixTeam,    B,      5,   0.3,    8
SevenTeam,  B,      6,   0.23,   9
EightTeam,  B,      7,   1.2,    4

作为 Pandas Dataframe 导入后,我将每个功能转换为这些列表: teams, group, id, score, diff.

使用这个堆栈溢出答案 Create a complex dictionary using multiple lists我可以创建以下字典:

{'EightTeam': {'diff': 4, 'id': 7, 'score': 1.2},
 'FiveTeam': {'diff': 7, 'id': 4, 'score': 0.5},
 'FourTeam': {'diff': 6, 'id': 3, 'score': 0.93},
 'OneTeam': {'diff': 4, 'id': 0, 'score': 0.25},
 'SevenTeam': {'diff': 9, 'id': 6, 'score': 0.23},
 'SixTeam': {'diff': 8, 'id': 5, 'score': 0.3},
 'ThreeTeam': {'diff': 5, 'id': 2, 'score': 0.64},
 'TwoTeam': {'diff': 10, 'id': 1, 'score': 1.0}}

使用代码:

{team: {'id': i, 'score': s, 'diff': d} for team, i, s, d in zip(teams, id, score, diff)}

但我所追求的是以“组”为主键,然后是团队,然后是团队内的 id、分数和难度(如上)。

我试过:

{g: {team: {'id': i, 'score': s, 'diff': d}} for g, team, i, s, d in zip(group, teams, id , 得分, 差异)}

但这不起作用,导致字典中每个组只有一个团队:

{'A': {'FourTeam': {'diff': 6, 'id': 3, 'score': 0.93}},
 'B': {'EightTeam': {'diff': 4, 'id': 7, 'score': 1.2}}}

下面是字典的外观,但我不确定如何到达那里 - 任何帮助将不胜感激!

{'A:': {'EightTeam': {'diff': 4, 'id': 7, 'score': 1.2},
  'FiveTeam': {'diff': 7, 'id': 4, 'score': 0.5},
  'FourTeam': {'diff': 6, 'id': 3, 'score': 0.93},
  'OneTeam': {'diff': 4, 'id': 0, 'score': 0.25}},
 'B': {'SevenTeam': {'diff': 9, 'id': 6, 'score': 0.23},
  'SixTeam': {'diff': 8, 'id': 5, 'score': 0.3},
  'ThreeTeam': {'diff': 5, 'id': 2, 'score': 0.64},
  'TwoTeam': {'diff': 10, 'id': 1, 'score': 1.0}}}

最佳答案

如果您的数据存储在这样的表中,则听写理解可能不是解决此问题的最佳方法。

尝试类似的东西

from collections import defaultdict
groups = defaultdict(dict)
for g, team, i, s, d in zip(group, teams, id, score, diff):
    groups[g][team] = {'id': i, 'score': s, 'diff': d }

通过使用 defaultdict,如果 groups[g] 已经存在,则将新团队添加为键,如果不存在,则会自动创建一个空字典,然后将新团队插入其中。

编辑:您编辑了您的答案,说您的数据在 Pandas 数据框中。您绝对可以跳过将列转换为列表的步骤。相反,您可以执行以下操作:

from collections import defaultdict
groups = defaultdict(dict)
for row in df.itertuples():
    groups[row.Group][row.Team] = {'id': row.ID, 'score': row.Score, 'diff': row.Difficulty} 

关于python - 从 Python 中的多个列表创建复杂的嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56294486/

相关文章:

python - C++ 中是否有与 python 中的 astype() 函数等效的函数?

python - 如果值是字符串列表,如何引用字典中的值?

python - 在 pyspark 中将行转置为列

python - 执行 Selenium 时意外的窗口位置移动

python - 如何为具有依赖项的 Python 项目创 build 置/安装程序?

python - 值错误: Unknown label type: 'continuous' while using Logistical Regression

python - Selenium 在 PC 和 RPI 上的性能差异

python - 如果 Firefox 实例已经打开,selenium 会抛出错误

dictionary - 如何在 ReasonML 中创建元组映射?

Python字典——如何防止新值覆盖旧值?