import os
contact = {}
def display_contact():
print("Name\t\tContact Number")
for key in contact:
print("{}\t\t{}".format(key,contact.get(key)))
while True:
choice = int(input(" 1.Add new contact \n 2. Search contact \n 3. Display contact\n 4. Edit contact \n 5. Delete contact \n 6. Sort List \n 7. Print \n 8. Exit \n Enter "))
if choice == 1:
name = input("Enter the contact name ")
phone = input("Enter number")
contact[name] = phone
elif choice == 2:
search_name = input("Enter contact name ")
if search_name in contact:
print(search_name, "'s contact number is ", contact[search_name])
else:
print("Name is not found in contact book")
elif choice == 3:
if not contact:
print("Empty Phonebook")
else:
display_contact()
elif choice == 4:
edit_contact = input("Enter the contact to be edited ")
if edit_contact in contact:
phone = input("Enter numer")
contact[edit_contact]=phone
print("Contact Updated")
display_contact()
else:
print("Name is not found in contact book")
elif choice == 5:
del_contact = input("Enter the contact to be deleted ")
if del_contact in contact:
confirm = input("Do you want to delete this contact Yes or No? ")
if confirm == 'Yes' or confirm == 'yes':
contact.pop(del_contact)
display_contact
else:
print("Name is not found in phone book")
else:
break
`
I have this but don't know where to if this is the right code to use or where to place it. I need help to sort the contact list by alphabet and add the print code, to print like to a printer. Any help? Thanks
strs = ['aa', 'BB', 'zz', 'CC']
print(sorted(strs)) ## ['BB', 'CC', 'aa', 'zz'] (case sensitive)
print(sorted(strs, reverse=True)) ## ['zz', 'aa', 'CC', 'BB']
I am not to good at coding and any help with be great, with the sorting and printing to a print will be great. Thanks for any help.
CodePudding user response:
You could write display_contact() like this.
def display_contact():
for name, number in sorted((k,v) for k, v in contact.items()):
print(f'Name={name}, number={number}')
You may want to pass a key parameter to sorted() depending on the sort order required.
Note that the function name is a misnomer because it prints all contacts