简体   繁体   English

使用对列表元素进行分组来创建嵌套字典

[英]Creating a nested dictionary with grouping the elements of list

i have a list that contains the teams of schools我有一个包含学校团队的列表

Teams = [["ThomasJeffersonHC", "Lucy"],
         ["ThomasJeffersonHC", "Elliot"],
         ["ThomasJeffersonHC", "Noah"],
         ["GilbertHC", "Kyle"],
         ["ThomasJeffersonHC", "Liam"],
         ["GilbertHC", "Bradley"],
         ["GilbertHC", "Eugene"]]

trying to group them in a dictionary by the first element of inner lists.尝试按内部列表的第一个元素将它们分组在字典中。

the dic's template be like below: dic 的模板如下:

d  = {"School_key": {"members": [group members list], "count": count of members }}
d = {}
lastkey = None
for key, member in Teams:
    if key != lastkey:
        if key not in d:
            d[key] = {1: {"members": [member], "count": 1}}
        else:
            number = max(d[key]) + 1
            d[key][number] = {"members": [member], "count": 1}
        lastkey = key
    else:
        number = max(d[key])
        d[key][number]["members"].append(member)
        d[key][number]["count"] += 1
print(d)

In this code, first I set d to an empty dict.在这段代码中,首先我将d设置为一个空的 dict。 Then I iterated through the Teams list, for every key if it is the same as the previous one I add a member to the pre-existing team, otherwise I create a new team and add the member into the team.然后我遍历Teams列表,对于每个键,如果它与前一个键相同,我将一个成员添加到预先存在的团队中,否则我创建一个新团队并将该成员添加到团队中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM