[英]How can I change int value of nested dictionary key? (Python 3)
我必须为我的评估项目编写一个基于菜单的“员工管理”程序。 主菜单项之一是“员工详细信息”,具有以下选项:
我已经完成了 1 和 2,但是在 3. 移除员工时,我遇到了特定的 function。 添加员工时,它会存储在employees_all
字典中,如下所示:
{1: {'fullname': 'John Smith', 'phonenumber': '0400 000 000', 'designation': 'Technician'},
2: {'fullname': 'Jane Doe', 'phonenumber': '0411 111 111', 'designation': 'Manager'},
3: {'fullname': 'Jimmy Smithers', 'phonenumber': '0422 222 222', 'designation': 'Maintenance'}}
添加员工时,我故意分配了一个升序的 int 键。 要删除员工,程序将员工 ID(键)作为输入,并从字典中删除该员工。
我想要的是,当(例如)员工 #2 被删除时,我希望员工 #3 的密钥变为 2,员工 #4 的密钥变为 3,依此类推。 我试图创建一些for
循环,从字典键中减去 1 大于已删除员工键的值,但我不断得到: unsupported operand type(s) for -: 'dict' and 'int'
每个菜单项都有自己的 function。 对于这个,它是remove_employee()
。 请参见下面的代码:
def remove_employee():
print("\n______________________________________________")
print("\n> MAIN MENU > EMPLOYEE DATA > REMOVE EMPLOYEE")
print("\n\nWhich employee would you like to delete?")
delnum = int(input("\n\nEmployee Number: "))
print("\n______________________________________________")
print("\n\nARE YOU SURE YOU WANT TO DELETE EMPLOYEE #",delnum,"?")
print("\n1. Yes\n2. No")
areyousure1 = input("\nEnter choice: ")
if areyousure1 == "1":
del(employees_all[delnum])
#### PLEASE HELP HERE ####
print("\n______________________________________________")
print("\nEMPLOYEE DATA SUCCESSFULLY DELETED")
time.sleep(1)
submenu1()
elif areyousure1 == "2":
print("\n______________________________________________")
print("\n--------- EMPLOYEE DATA NOT DELETED ----------")
time.sleep(1)
submenu1()
else:
print("\n______________________________________________")
print("\nINVALID INPUT! PLEASE ENTER A VALID NUMBER.")
time.sleep(1)
remove_employee()
您的数据结构不是最优的。 在我看来,最好的方法是使用数组并将 ID 字段添加到您的员工 object。
employees = [
{"id": 1, 'fullname': 'John Smith', 'phonenumber': '0400 000 000', 'designation': 'Technician'},
{"id": 2, 'fullname': 'Jane Doe', 'phonenumber': '0411 111 111', 'designation': 'Manager'},
{"id": 3, 'fullname': 'Jimmy Smithers', 'phonenumber': '0422 222 222', 'designation': 'Maintenance'}
]
def delete_employee(id):
employees = [emp for emp in employees if emp.id != id]
# the new employees list is without the id you have removed
但是,如果您出于任何原因想要保留此数据结构,则可以使用以下代码:
employees = {1: ...}
def delete_employee(id):
employees = {emp_id, employees[id] for emp_id in employees if emp_id != id}
# the new employees list without unwanted employee
我强烈建议您为此目的使用列表。
employees_all =
[{'fullname': 'John Smith', 'phonenumber': '0400 000 000', 'designation': 'Technician'},
{'fullname': 'Jane Doe', 'phonenumber': '0411 111 111', 'designation': 'Manager'},
{'fullname': 'Jimmy Smithers', 'phonenumber': '0422 222 222', 'designation': 'Maintenance'}]
这不仅负责索引,在使用del
删除条目后,索引也会移动:
del employees_all[index]
如果我理解正确,您需要在delnum
之后 -1 所有employees_all
键。 有关如何更改字典键的信息,请参阅此答案。 你的回答是:
for i in range(delnum+1,len(employees_all)):
employees_all[i-1]=employees_all.pop(i)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.