In: Computer Science
Write a program that:
(a) Reads name and age of 10 different persons
(b) Stores this information in a dictionary (remember, dictionary contains keys and values)
(c) Sorts your dictionary based on keys
(d) Sorts your dictionary based on values
(e) Displays the original and both sorted dictionaries (step c and d)
(f) You search for a specific person and the program displays their name and age on the screen. If the person’s information is not in the dictionary, the program displays “Person not Found”.
NOTE
Answer should be in python. and according to the different types of sorting algorithms including Monkey Sort, Bubble Sort and Selection Sort.
# I have created a list of tuples to just for example.
persons = [('jack', 32), ('rachel', 35), ('ross', 22), ('raphael', 54), ('andrew', 28), ('jackson', 52),
('mike', 12), ('emma', 29), ('monica', 30), ('ryan', 43)]
#This function wil read and convert the list into a dictionary.
def read_person(persons):
person_dict = {}
for i in persons:
person_dict[i[0]] = i[1]
return person_dict
# this function will sort the dictionary using keys. I am using sorted function to sort the dict.It may not be available in older python version.
def sort_keys(person_dict):
dict_by_keys = {}
sorted_keys = sorted(person_dict.items())
for i in sorted_keys:
x = i[0]
y = i[1]
dict_by_keys[x] = y
return dict_by_keys
# this function will sort the dictionary using values. I am using sorted function to sort the dict.It may not be available in older python version.
def sort_values(person_dict):
dict_by_values = {}
d_sorted_by_value = sorted(person_dict.items(), key=lambda x: x[1])
for i in d_sorted_by_value:
x = i[0]
y = i[1]
dict_by_values[x] = y
return dict_by_values
# displaying all the dictionaries.
person_dict = read_person(persons)
sort__by_key = sort_keys(person_dict)
sort_by_value = sort_values(person_dict)
print("Original Dict:", person_dict)
print()
print("Sorted by keys dict:",sort__by_key)
print()
print("Sorted by values dict:",sort_by_value)
#This function will search the entered name and display it's name along with it's age. It will ask for an input
def search_person(person_dict):
key = input('Enter the name:')
if key in person_dict.keys():
print("Name: {}, Age: {}".format(key, person_dict[key]))
else:
print("Person not found")
search_person(person_dict)
Please let me know ,If you have any doubts.