【发布时间】:2017-11-15 09:01:37
【问题描述】:
对于我程序的这一部分,我需要编写允许用户更新字典的代码。关键是员工 ID,可更新字段是他们的姓名、部门和职位。这样当查看更新的记录时,它会显示新的名称、职位和部门。员工在哪里是字典。这是我到目前为止所拥有的:
while Choice == '2':
dict_key = input('Enter the employee ID of the employee to change the record: ')
if dict_key in Employees:
n = 3
print('Enter the new Name, Department, and Title')
for i in range(n):
updates = input().split(' ')
Employees[dict_key] = updates[0][1][2]
print('\n')
else:
print('ERROR: That record does not exist!')
print('\n')
Continue = input('Press 1 to update another employee record or 2 to exit: ')
print('\n')
if Continue == '2':
print('*' * 80)
break
运行此代码时出现以下错误:
Traceback (most recent call last):
line 43, in <module>
Employees[dict_key] = updates[0][1][2]
IndexError: string index out of range
ex 的期望输出: 如果员工 ID 1234 = John,IT,Programmer 更新内容是:John Doe,IT 经理。
在更新条目后,员工 ID 1234 应该 = John Doe,IT,Manager。
编辑 我试图以一种用户可以单独输入更新(名称第一,标题第二......)并使用所有三个输入更新键值(1234)的字典的方式进行编程,以获得我想要的输出。
对不起,如果我的代码是一团糟,我现在正在学习 python。如果我的帖子一团糟,也很抱歉,也是第一次来这里。
【问题讨论】:
-
如果更新包含
,,那么你应该split(',');另外,您正在 for 循环中覆盖updates -
你没有做你认为你正在做的事情。
updates[0]会给你第一个字符串 ("John Doe"),然后updates[0][1]会给你"J",最后updates[0][1][2]给你一个IndexError,因为[2]超出了字符串的末尾。如果您打算将数据存储为元组,那么只需使用Employees[dict_key] = updates就可以了。我认为你真正想做的是updates[0], updates[1], updates[2])。注意:您的方法和拆分还有其他问题。您应该单独询问每个字段(姓名、部门、职位)并避免拆分。
标签: python dictionary