简体   繁体   English

如何更改嵌套字典键的 int 值? (Python 3)

[英]How can I change int value of nested dictionary key? (Python 3)

I have to write a menu-based 'Employee Management' program for one my assessment pieces.我必须为我的评估项目编写一个基于菜单的“员工管理”程序。 One of the main menu items is 'Employee Details', with the following options:主菜单项之一是“员工详细信息”,具有以下选项:

  1. Show employees显示员工
  2. Add new employees添加新员工
  3. Remove employees移除员工

I've already completed 1, & 2, but I'm stuck with a specific function in 3. Remove employees.我已经完成了 1 和 2,但是在 3. 移除员工时,我遇到了特定的 function。 When an employee is added, it's stored in the employees_all dictionary as such:添加员工时,它会存储在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'}}
        

I deliberately assigned an ascending int key when an employee is added.添加员工时,我故意分配了一个升序的 int 键。 To remove an employee, program takes the employee id (the key) as input, and deletes that employee from the dictionary.要删除员工,程序将员工 ID(键)作为输入,并从字典中删除该员工。

What I want , is that when (for instance) employee #2 is deleted, I want employee #3's key to become 2, for employee #4's key to become 3, etc, so on and so forth.我想要的是,当(例如)员工 #2 被删除时,我希望员工 #3 的密钥变为 2,员工 #4 的密钥变为 3,依此类推。 I've tried to create some for loops that subtract 1 from dictionary keys greater than the value of the deleted employee's key, but I keep getting: unsupported operand type(s) for -: 'dict' and 'int'我试图创建一些for循环,从字典键中减去 1 大于已删除员工键的值,但我不断得到: unsupported operand type(s) for -: 'dict' and 'int'

Each menu item has it's own function.每个菜单项都有自己的 function。 For this one, it's remove_employee() .对于这个,它是remove_employee() See code below:请参见下面的代码:

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()

Your data structure isn't optimal.您的数据结构不是最优的。 The best way you could come with in my opinion is to use array and add ID field to your employee object.在我看来,最好的方法是使用数组并将 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

However, if you want to kee pthis data structure for any reason, you can use this code:但是,如果您出于任何原因想要保留此数据结构,则可以使用以下代码:


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

I would stronly recommend you to use a list for this purpose.我强烈建议您为此目的使用列表。

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'}]

This not only takes care of the indexing, indeces are also shifted after deleting entries with del :这不仅负责索引,在使用del删除条目后,索引也会移动:

del employees_all[index]

If I understand correctly you need to -1 all employees_all keys after delnum .如果我理解正确,您需要在delnum之后 -1 所有employees_all键。 Refer to this answer on how to change dictionaries key.有关如何更改字典键的信息,请参阅此答案 your answer is:你的回答是:

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.

相关问题 如何在Python中切换嵌套字典的值和键? - How can one switch the value and key of a Nested dictionary in Python? 如何使用变量中的值更新嵌套 Python 字典中的键? - How can i update key in nested Python dictionary with a value from a variable? 如何通过具有相应键的字典值更改列中的值? Python - How I can change value in column by a value of dictionary with corresponding key ? Python 如何使用单个键访问嵌套字典中的值? - How can I access value in nested dictionary using a single key? 我可以用 python 中具有相同键的另一个字典的值更改字典的键吗? - Can I change the Key of a Dictionary with the value of another Dictionary that has the same Key in python? 如何更改在 Python 中排序的嵌套字典的打印格式 - How Can I Change The Print Format Of A Nested Dictionary That Is Sorted In Python 如何将字典中的列表更改为键和他的值? - How can I change a list in a dictionary into a key and he's value? 如何在python中将字典键值从列表更改为单个int或float? - How to change dictionary key value from a list to a single int or float in python? 如何在 python 中将嵌套列表作为字典值进行迭代和排序? - How can i iterate and order nested list as a dictionary value in python? 如何通过切片在字典 python 中分别获取键和值 - how can i get the key and value separately in dictionary python by slicing
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM