【发布时间】: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