在准备答案时,我没有注意到一个正确的答案已经发布并被接受。不过,在下面发布我的答案版本,增加了连续提问的功能和退出程序的能力。
Patt = [
{'Phone': "0718604545", 'Name': "Tom", 'Age': '2007'},
{'Phone': "0718123567", 'Name': "Katy", 'Age': '1998'},
{'Phone': "0718604578", 'Name': "BillyW", 'Age': '1970'},
{'Phone': "0714565778", 'Name': "Sony", 'Age': '1973'}
]
print(Patt)
def search_phone_records(user_phone):
for record in Patt: # Iterate over all the phone records in the dictionary
if user_phone == record['Phone']: # stop if found phone number in the dictionary
return record['Name'] # Return user's name from the phone record
return None
while True:
user_input = input("Enter Phone or press 'x' to exit: ")
if user_input in ('x', 'X'):
print("Have a nice day!!! Thank you using our service!!!")
break # End the programme
# Search for the phone number
user_name = search_phone_records(user_input)
#print("[{0}]".format(user_name))
if type(user_name) == type(None): # Phone number is not found
print("Oops!!! Entered phone number ({0}) is not found in the dictionary!!!".format(user_input))
else: # Phone number is found
print("Entered phone number ({0}) is found in the dictionary!!!".format(user_input))
print("It is {1}'s phone number.".format(user_input, user_name))
使用字典理解的另一种解决方案:
Patt = [
{'Phone': "0718604545", 'Name': "Tom", 'Age': '2007'},
{'Phone': "0718123567", 'Name': "Katy", 'Age': '1998'},
{'Phone': "0718604578", 'Name': "BillyW", 'Age': '1970'},
{'Phone': "0714565778", 'Name': "Sony", 'Age': '1973'}
]
print(Patt)
def search_phone_records_using_dictionary_comprehension(user_phone):
return {'Name': record['Name'] for record in Patt if user_phone == record['Phone']}
while True:
user_input = input("Enter Phone or press 'x' to exit: ")
if user_input in ('x', 'X'):
print("Have a nice day!!! Thank you using our service!!!")
break # End the programme
result = search_phone_records_using_dictionary_comprehension(user_input)
print("result = {0}".format(result))
if len(result) == 0: # Phone number is not found
print("Oops!!! Entered phone number ({0}) is not found in the dictionary!!!".format(user_input))
else: # Phone number is found
print("Entered phone number ({0}) is found in the dictionary!!!".format(user_input))
print("It is {1}'s phone number.".format(user_input, result['Name']))