首页 > 解决方案 > 如何更改字典中的布尔值?

问题描述

我正在用python制作一个待办事项列表,以及修改它的方法。功能之一是检查任务。这是字典:

checked = bool

todolist = {
    0: {
        "task": "Finish this program",
        checked: False
    }
}

这是检查或取消选中任务的功能:

try:
    checkindex = int(input("Todo index >> "))
    todolist[checkindex].get(checked) = not todolist[checkindex].get(checked)
except ValueError or IndexError:
    print("ERROR: Not a valid index")

如果我再次看到检查任务,这就是我想看到的:

todolist = {
    0: {
        "task": "Finish this program",
        checked: True
    }
}

todolist[checkindex].get(checked)但是,我在说“无法分配给函数调用”时收到错误消息。我该如何解决?

标签: pythondictionary

解决方案


当您这样做时checked = bool,您不会将其声明checked为布尔值,而是将内置bool函数别名为 name checked。这只是巧合。相反,只需使用字符串键:

todolist = {
    0: {
        "task": "Finish this program",
        "checked": False
    }
}

当您切换任务时,您只需分配给"checked"键:

try:
    checkindex = int(input("Todo index >> "))
    todolist[checkindex]["checked"] = not todolist[checkindex]["checked"]
except (ValueError, IndexError):
    print("ERROR: Not a valid index")

我也修复except ValueError or IndexError了,这不会像你期望的那样。


推荐阅读