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

时间:2019-05-24 14:16:46

标签: 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, score, diff)}

但这是行不通的,并且导致字典中每个组只有一个团队:

{'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}}}

2 个答案:

答案 0 :(得分:3)

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

尝试类似

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]已经存在,则将新团队添加为密钥,如果不存在,则会自动创建一个空的dict,然后将新团队插入其中。

编辑:您编辑了答案,以说您的数据在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} 

答案 1 :(得分:1)

如果您绝对想使用理解,那应该可以:

wd.execute_script("arguments[0].click();", elem)

为清楚起见,我添加了换行符

编辑:

发表评论后,为了更好地阐明我的意图和好奇心,我进行了比较:

elem.click()

executable version

输出:

z = zip(teams, group, id, score, diff)
s = set(group)
d = { #outer dict, one entry for each different group
    group: ({ #inner dict, one entry for team, filtered for group
        team: {'id': i, 'score': s, 'diff': d} 
        for team, g, i, s, d in z
        if g == group
        }) 
    for group in s 
    }

就性能而言,它们看起来确实相同。在上面的句子中,我只是强调了这作为@JohnO已经发布的解决方案的替代解决方案。