[英]Matching User 's Input With Nested Dictionary in Python3.7
我似乎無法將用戶input(num)
與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')
沒有錯誤,但是輸出與預期不匹配。
您無需遍歷字典。
您可以改用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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.