【问题标题】:Adding a dictionary to a list inside of a dictionary将字典添加到字典内的列表中
【发布时间】:2018-08-27 11:30:10
【问题描述】:

我正在循环浏览一个包含学生家长详细信息的 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'

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

【问题讨论】:

  • 您尝试追加到字典。你定义 data[row['ID']] = {}
  • 应该是:data[row["ID"]] = []
  • 谢谢,就是这样!错误消息应该已经放弃了。我不知道为什么我看不到。

标签: python python-3.x dictionary append


【解决方案1】:

正如 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-28
    • 1970-01-01
    • 1970-01-01
    • 2015-04-02
    • 2018-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多