【问题标题】:error: 'str' object has no attribute 'update' when adding key to dict错误:将键添加到 dict 时,“str”对象没有属性“update”
【发布时间】: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


【解决方案1】:

这个怎么样...

for child in children:
    courseProgress[child.id] = {
                   name: str(child.child_firstname),
                   courses: {}
                 }

然后

courseProgress[individualCourse.child.id]['courses'].update({currentCourseID : thisCourse})

【讨论】:

  • 对我有用的是:对于儿童中的孩子: courseProgress[child.id] = dict()
  • 我会将您的答案标记为正确,因为虽然与我的最终代码不完全相同,但它仍然有效......声明空字典的最终效果是修复它......谢谢也给 Martijn Pieters!
【解决方案2】:

您正在尝试 update() 字符串而不是字典。 我认为你应该有一个不同的数据结构,现在你有一个字典,其中键是整数,值是字符串。 你需要一个字典。

{key1: {}, key2: {}}

您可以简单地更改 {} 的 str()。

另一种不要混淆“名称”和“原因”的方法是做类似的事情

for child in children:
    courseProgress[child.id] = {
        'name': child.child_firstname,  #child_name
        'courses': {}  #map of courses course_id: course
    }

那么你可以这样做:

courses = courseProgress[individualCourse.child.id]['courses']
courses.update({currentCourseID:thisCourse})

如果您想要给定 child.id 和课程的信息,您可以这样做 couseProgress[childId]['courses'][someCourseId]

与其拥有那种复杂的数据结构,有时不如创建一个类:)。

【讨论】:

    猜你喜欢
    • 2018-09-01
    • 2016-04-07
    • 2015-08-05
    • 2021-07-19
    • 1970-01-01
    • 2019-07-30
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多