while preparing answer, I did not notice that one correct answer was already posted and accepted. Though, posting my version of the answer below with added feature of continuous questioning and an ability to exit from the program.
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))
Another solution using dictionary comprehension:
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']))