2017-10-31 2 views
0

저는 직원 정보 (이름, 부서, 직위, 급여)가 포함 된 사전 목록 인 dep_list를 정렬하려고합니다. 지금 나는 이름으로 정렬했다고 믿지만 성으로 정렬하고 싶습니다. 가능하다면 '이름'을 2 개의 다른 문자열로 분리하지 않아도됩니다.Python 사전의 성 목록 별 정렬

#Function for adding employee information 
def add_emp(): 
    #Ask the user to add an employee 
    print("Enter the employee's information:\n") 
    #Input first and last name 
    name = str(input("What is the employee's name? ")).title() 
    #Input employee position 
    position = str(input("What is their position? ")).title() 
    #Input employee department 
    em_department = str(input("What is their department? ")).title() 
    #Make sure the salary is numeric 
    try: 
     #Input employee salary 
     salary = round(float(input("What is their salary? ")), 2) 
     #Add information to a dictionary called employees 
     employees[name] = {"name": name, "position": position,  "em_department": em_department, "salary": salary} 
    except: 
     print("Salaries must be numeric, silly!") 

#Function for adding employees to dictionary by department 
def dep_emp(): 
    #Go through all department names stored in the tuple 
    for x in dep_tup: 
     #Initialize department list each time to ensure correct sorting 
     dep_list = [] 
     #Go through all employee dictionaries; when matched, add to the list associated with the corresponding key in the dep_dict dictionary 
     for names in employees: 
      if x == employees[names]["em_department"]: 
       dep_list.append(employees[names]) 
       dep_list.sort(key=operator.itemgetter('name')) 
       dep_dict[x] = dep_list 
       continue 

참고 : 사전의 목록은 다음과 같습니다 {

department1 : [{ '이름'이름 'em_department'부서 '위치'위치 '급여'급여를 }, ...,

department2 : [...]

}

답변

3

이 수행해야합니다

dep_list.sort(key=lambda x: x['name'].split()[-1]) 

dep_list의 각 사전에 대한 설명

name 키와 관련된 값을 찾아, 그것을 분할하고, 종류 (마지막 이름이어야합니다) 분할의 마지막 문자열을 기반으로 .