【发布时间】:2015-07-29 20:39:46
【问题描述】:
这是一个新手问题,所以请多多包涵……
我将 python 2.7.8 与 Django 1.7.1 一起使用。
我正在尝试在 for 循环中向 dict 添加一个键。
courseProgress = dict()
for child in children:
courseProgress[child.id] = str(child.child_firstname)
for individualCourse in allCourses:
#get the total number of items within a course
totalContentsCount = len(courseContents[individualCourse.course_id])
#get the total number of completed steps for this course from the rewardHistory that we obtained earlier
thisCourseProgress = len(allCourses.filter(course = individualCourse.course_id))
#divide to get a percentage
thisProgress = float(thisCourseProgress) / float(totalContentsCount)
currentCourseID = int(individualCourse.course_id)
thisCourse = {
'progress' : thisProgress,
'courseInfo' : courseContents[currentCourseID]
}
courseProgress[individualCourse.child.id].update({currentCourseID : thisCourse})
最后一行产生错误:error: 'str' object has no attribute 'update'
显然(?)它看到 courseProgress[individualCourse.child.id] 作为一个字符串,而不是作为我试图添加子键的字典中的键。我认为这是因为我得到了返回的值(这是一个字符串)。在交互式提示中,我得到以下信息:
>>>courseProgress[individualCourse.child.id]
'Sophie'
我不知道这是为什么......
我追求的结果是向courseProgress[individualCourse.child.id] 添加一个子密钥(例如courseProgress[1]),该子密钥的最终格式为{1 : thisCourse}
我做错了什么?
【问题讨论】:
-
只有当
courseProgress[individualCourse.child.id]的结果是字典本身时,您的行才会起作用 -
courseProgress[child.id] = str(child.child_firstname)将您的值设置为 strings。字符串确实没有update方法。这里想要发生什么? -
如果您希望这些值是字典,那么您实际上必须在那里创建一个字典,而不是字符串。
-
非常感谢大家。看起来这种情况的根本原因是简单地将值从 str() 更改为 dict()。我会试一试
标签: python django python-2.7 dictionary