在Python3.7中将用户输入与嵌套字典进行匹配

时间:2019-05-29 23:29:12

标签: python python-3.7

我似乎无法将用户input(num)id_num匹配以打印出单独的许可证信息。我希望当系统提示用户输入许可证号时,代码应在字典中循环查找并找到其匹配项,并打印与输入内容匹配的信息。

我尝试过:

  1. 如果driver_license [id_num]中为num:
  2. 如果num == id_num:
  3. 如果num == int(id_num):
42456 :{'name': 'jill', 'ethnicity': 'hispanic','eye': 'yellow' ,'height': '6.1'},

44768 :{'name': 'cheroky', 'ethnicity': 'native','eye': 'green' ,'height': '6.7'},

32565 :{'name': 'valentina', 'ethnicity': 'european','eye': 'fair','height': '4.9'}}


print('\n')
print('- ' *45)


for id_num, id_info in driver_license.items():
    num = int(input('Enter your driving license number: '))

    print(f"Id number: {id_num}")
    name=f"{id_info['name']}"
    origin= f"{id_info ['ethnicity']}"
    eye= f"{id_info['eye']}"
    height=f"{id_info['height']}"

    if num in driver_license[id_num]:
        print(f'\nId number is:{num}')
        print(f'Name: {name}')
        print(f'Ethnicity: {origin}')
        print(f'Eyes color: {eye}')
        print(f'Height: {height}\n')
    else:
        print('Invalid ID')

没有错误,但是输出与预期不匹配。

1 个答案:

答案 0 :(得分:0)

您不需要遍历字典。

您可以改用get(key, default)使用输入的许可证号作为密钥从driver_license词典中获取条目。然后,您可以将default设置为某个值,以处理密钥不在dict中的情况(在这里我使用None)。

driver_license = {
    "42456" : {'name': 'jill', 'ethnicity': 'hispanic','eye': 'yellow' ,'height': '6.1'},
    "44768" : {'name': 'cheroky', 'ethnicity': 'native','eye': 'green' ,'height': '6.7'},
    "32565" : {'name': 'valentina', 'ethnicity': 'european','eye': 'fair','height': '4.9'}
}

id_num = input('Enter your driving license number: ')
# if user enters "32565"

id_info = driver_license.get(id_num, None)  
# id_info would be:
#    {'name': 'valentina', 'ethnicity': 'european','eye': 'fair','height': '4.9'}

if id_info:
    print(f'\nId number is:{id_num }')
    print(f'Name: {id_info["name"]}')
    print(f'Ethnicity: {id_info["ethnicity"]}')
    print(f'Eyes color: {id_info["eye"]}')
    print(f'Height: {id_info["height"]}\n')
else:
    print('Invalid ID')