In: Computer Science
Dictionaries in python can store other complex data structures as the VALUE in a (KEY, VALUE) pair.
2.1) Create an empty dictionary called 'contacts'.
The KEY in this dictionary will be the name of a contact (stored as a string). The VALUE in this dictionary will be a list with three elements: the first element will be a phone number (stored as a string), the second an email address (stored as a string) and the third their age (stored as an integer).
2.2) Insert information for three imaginary contacts of yours in the dictionary contacts.
2.3) Using input(), ask the user to enter an age. Then, using a for loop and (inside the for loop) an if statement, print the name and phone number for all contacts that are either of that age or older. If no contacts of or above that age are found, your code should report that to the user. For example, suppose you have three friends in contacts with the data:
Name: Julia Phone: 384-493-4949 Email: [email protected] Age: 34 Name: Alfred Phone: 784-094-4520 Email: [email protected] Age: 49 Name: Sam Phone: 987-099-0932 Email: [email protected] Age: 28
Then, your code asks the user to specify a minimum age. In the example below, the user enters the age '30':
What is the minimum age? 30
Your code should then print the name and phone number of everyone who is 30 years old or older:
Julia is 34 years old and can be reached at 384-493-4949. Alfred is 49 years old and can be reached at 784-094-4520.
If the user were to enter (for example) 50 at the prompt above, your code should have instead printed the message:
Sorry, you do not have any contacts that are 50 or older.
CODE
# creating empty dictionary
contacts = {}
# adding 3 contacts to the dictionary
contacts["Julia"] = ["384-493-4949", "[email protected]", 34]
contacts["Alfred"] = ["784-094-4520", "[email protected]", 49]
contacts["Sam"] = ["987-099-0932", "[email protected]", 28]
# reading age from user
age = int(input("What is the minimum age: "))
# setting found to 0
found = 0
# retrieving each record from the dictionary
for key in contacts:
# checking if any age in contacts are greater than or equal to user given age
if(contacts[key][2] >= age):
# if yes, then prints the output
print(key, "is", contacts[key][2], "years old can be reached at", contacts[key][0], ".")
# setting flag to 1
found = 1
# checking if found is 0, if yes it prints not contact found
if(found == 0):
print("Sorry, you do not have any contacts that are", age, "or older.")
CODE SCREENSHOT
OUTPUT