用户输入名称时,如何获取键值?

例如我有这个嵌套的字典:

D = {'emp1': {'name': 'Bob', 'job': 'Mgr'},
     'emp2': {'name': 'Kim', 'job': 'Dev'},
     'emp3': {'name': 'Sam', 'job': 'Dev'}}

当用户输入姓名(例如:“鲍勃”)时,如何打印所有信息? 例如,要求用户输入员工姓名以搜索有关该姓名的所有信息:

Employee ID: emp1
Employee Name: Bob
Job: Mgr
评论
aeius
aeius

这样的事情会做:

name = input('Enter employee name: ')
for k, v in D.items():
    if v['name'] == name:
        print('Employee ID:', k)
        print('Employee Name:', v['name'])
        print('Job:', v['job'])

input('your prompt message') will prompt the user for user input and return the entered value.

点赞
评论
习惯性隐身
习惯性隐身

loop over your dictionary using items:

for key, value in D.items():
    if "Bob" in value['name']:
        print(f"Employee ID: {key}")
        print(f"Employee Name:: {value['name']}")
        print(f"Employee ID: {value['job']}")
点赞
评论