给定员工信息字典列表,如何使用DICT或list组合(如适用)按ID号查找



案例:我需要使用input()获得员工ID的用户输入,以查看字典中包含的员工详细信息。

问题:但是input()的输出是一个字符串。如何将员工ID与查找字典中已包含的信息联系起来。我尝试使用LIST,但没有成功。

代码:

给定的包含员工详细信息的字典(员工ID号(列表

ID001 ={'Name':'John Clause', 'Age':'21' , 'Gender':'Male'}    
ID002 ={'Name':'Greg Pyuse' , 'Age':'21' , 'Gender':'Male'}    

用字典填充列表">

List = [ID001,ID002]

要求用户输入((以请求字典,即"ID001"或"ID002">

ID = input()

我想显示与用户输入的词典相对应的列表索引

ID_Index=List.index(ID)

如果我跑步:

ValueError Traceback(最近调用最后(3.4#获取身份证号码列表索引---->5 ID_Index=列表索引(ID(6打印(类型(ID((7#显示具有特定索引的列表内容

ValueError:"ID002"不在列表中

如果您想通过键查找条目,您应该使用dict:

Dict = {
'ID001': {'Name':'John Clause', 'Age':'21' , 'Gender':'Male'},
'ID002': {'Name':'Greg Pyuse' , 'Age':'21' , 'Gender':'Male'}
}

以便如果IDID001,则可以使用Dict[ID]来获得dict{'Name':'John Clause', 'Age':'21' , 'Gender':'Male'}

我通过bhlsing为未来的观众详细阐述了我的解决方案

定义字典

info_Dict={}
Student={}

创建具有三个关键字和值的字典

for any_variable in range(0,3):
id=input('Enter I.D. ') 
#Populate dictionary (info_Dict) with student's information using input()
info_Dict['Name']=input("Name: ") 
info_Dict['Age'] =input("Age: ")
info_Dict['Course']=input("Course: ")
#Add (info_Dict) to another dictionary (Student) whose keys are student's I.D.
Student['ID00'+id]=(info_Dict)
#Empty Dictionary of students (info_Dict) so we can add new entry 
#on next loop - it act as temporary variable.
info_Dict={}  
print(Student)

如果我运行,它将在3个循环中请求输入,我输入如下:

Enter I.D. 1
Name: MATT MONROE 
Age: 88
Course: PYTHON 
Enter I.D. 2
Name: JAMES COOPER 
Age: 68
Course: JAVA 
Enter I.D. 3
Name: CATE HOLMES 
Age: 52
Course: AUTOMOTIVE 
{'ID001': {'Name': 'MATT MONROE ', 'Age': '88', 'Course': 'PYTHON '},
'ID002': {'Name': 'JAMES COOPER ', 'Age': '68', 'Course': 'JAVA '},
'ID003': {'Name': 'CATE HOLMES ', 'Age': '52', 'Course': 'AUTOMOTIVE '}}

我现在可以根据身份证号码进行编辑

Student['ID002']={'NAME':input('NAME'),'Age':input('Age'), 'Course':input('Course')}
Student

如果我运行它,它将询问输入,然后它将覆盖ID002 的先前数据

NAMEANNE CURTIS 
Age32
CourseFINE ARTS 
{'ID001': {'Name': 'MATT MONROE ', 'Age': '88', 'Course': 'PYTHON '},
'ID002': {'NAME': 'ANNE CURTIS ', 'Age': '32', 'Course': 'FINE ARTS '},
'ID003': {'Name': 'CATE HOLMES ', 'Age': '52', 'Course': 'AUTOMOTIVE '}}

最新更新