将字典添加到字典内的列表中

时间:2018-03-18 23:33:10

标签: python python-3.x dictionary append

我正在循环浏览一个CSV文件,其中包含学生家长的详细信息,并将数据加载到以学生ID作为密钥的字典中。

每个字典值都有一个父母列表。每个父母都是一个字典,其中包含姓名和电子邮件地址。我可以添加第一个父项没有问题,但当我尝试将第二个父项追加到列表时,我收到一个错误。这是我的代码:

def parentsFile(location):
    with open(location) as readfile:
        doc = csv.DictReader(readfile, delimiter=",")
        data = {}
        # Read the data and add to multi-dimentional dictionary
        for row in doc:
            if row["ID"] not in data:  # No previous entry for student
                data[row["ID"]] = {}
                data[row["ID"]][0] = {}
                data[row["ID"]][0]["lastName"] = row["Last_Name"]
                data[row["ID"]][0]["firstName"] = row["First_Name"]
                data[row["ID"]][0]["email"] = row["Email_Address"]
            else:   # There is a previous entry, this is the second parent entry
                new = {}
                new["lastName"] = row["Last_Name"]
                new["firstName"] = row["First_Name"]
                new["email"] = row["Email_Address"]
                data[row["ID"]].append(new)
    return data

这是我收到的错误消息:

data[row["ID"]].append(new)
AttributeError: 'dict' object has no attribute 'append'

我的所有谷歌搜索都告诉我,我可以附加到字典中的列表中。我的问题是将字典添加到字典内的列表中吗?

1 个答案:

答案 0 :(得分:0)

正如哈姆扎和斯蒂芬指出的那样,我已经将我的第二级声明为字典而不是列表。这导致了我的错误。我已将代码更改为:

for row in doc:
            if row["ID"] not in data:  # No previous entry for student
                new = {}
                new["lastName"] = row["Last_Name"]
                new["firstName"] = row["First_Name"]
                new["email"] = row["Email_Address"]
                data[row["ID"]] = []
                data[row["ID"]].append(new)
            else:   # There is a previous entry, this is the second parent entry
                num = len(data[row["ID"]])
                new = {}
                new["lastName"] = row["Last_Name"]
                new["firstName"] = row["First_Name"]
                new["email"] = row["Email_Address"]
                data[row["ID"]].append(new)