python - 如何更改字典中的布尔值?
问题描述
我正在用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)
但是,我在说“无法分配给函数调用”时收到错误消息。我该如何解决?
解决方案
当您这样做时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
了,这不会像你期望的那样。
推荐阅读
- ftp - 无法在genexus上使用ftp保存文件
- r - 从带有逗号分隔列表的单元格进行 Vlookup 或表连接
- css - Flex div 无法正确渲染
- c# - C# 在 Microsoft.Office.Interop.Word.List 的列表项中获取第二段
- terraform - 将新权限附加到 AWS 中的角色
- r - 从点到原点的ggplot线和余弦分数
- r - 在 data.table 中创建链索引/迭代组中的行
- android - 我可以在不启动新包名称的情况下对我的应用程序进行全面改造吗?
- c++ - 线性斐波那契实际代码的伪代码
- apache-spark - 如何在 Kubernetes 上运行 Spark Standalone master,它将使用 Kubernetes Cluser Manager 来启动 worker