Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将词典添加到词典内的列表_Python_Python 3.x_Dictionary_Append - Fatal编程技术网

Python 将词典添加到词典内的列表

Python 将词典添加到词典内的列表,python,python-3.x,dictionary,append,Python,Python 3.x,Dictionary,Append,我正在浏览一个CSV文件,其中包含学生家长的详细信息,并将数据加载到以学生ID为键的词典中 每个字典值都有一个父项列表。每一位家长都是一本字典,上面有他们的名字和电子邮件地址。我可以添加没有问题的第一个父级,但是当我尝试将第二个父级附加到列表中时,我得到了一个错误。这是我的代码: def parentsFile(location): with open(location) as readfile: doc = csv.DictReader(readfile, delimi

我正在浏览一个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'

我所有的谷歌搜索都告诉我,我可以在字典里的列表中添加词尾。是不是我的问题在于将词典添加到词典中的列表中?

正如Hamza和Stephen所指出的,我已经声明我的第二级是词典而不是列表。这导致了我的错误。我已将代码更改为:

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)

您正在尝试附加到词典中。您定义的数据[row['ID']={}应该是:
data[row['ID']]=[]
谢谢,就这样!错误消息应该已经泄露了它。我不知道为什么我看不到。