You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3.7中替换字典空元素失败,请求技术帮助

问题解决:控制台输入赋值到Python字典

先梳理你代码里的几个核心问题:

  • 字典A的键名存在语法错误:'name : ''多了冒号,' 'age'多了空格,这些错误会导致后续访问键时找不到对应项
  • 赋值语句用错了语法:A['name'] : A[name]不是合法的赋值写法,Python里赋值要用=,且你需要把输入的变量值直接赋给字典键,而非去字典里找name这个不存在的键
  • 数值类型未转换:age和任务数量的初始值是整数,但input()返回的是字符串,直接赋值会导致类型不匹配
  • 错误引用了不存在的字典键:A['a']是无效键,应该对应字典里的'age'

修正后的完整代码:

import datetime
import time

# 修正字典键名的语法错误
A = {'name': '', 'age': 0, 'tasks done': '', 'number of tasks done': 0}

print("hello 'Worker'")
time.sleep(2)

# 获取用户输入
name = input("enter name: ")
# 把输入的年龄转成整数类型
age = int(input("enter age: "))
tasksdone = input("enter all names given to the tasks you've completed so far: ")
# 任务数量转成整数类型
no_of_tasks_done = int(input("enter the number of tasks done: "))

# 将输入值赋值到字典对应的键
A['name'] = name
A['age'] = age
A['tasks done'] = tasksdone
A['number of tasks done'] = no_of_tasks_done

x = datetime.datetime.now()
print(x)
# 打印字典验证结果
print("更新后的字典:", A)

运行这段代码后,控制台输入的内容就能正确替换字典里的初始空值和0值了。

内容的提问来源于stack exchange,提问作者mr. code

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 15:07:53