Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # phone_book_tutor.py
- """
- phone_book.txt:
- bp1=xxx
- bp2=ooo
- ch=zzz
- me=aaa
- mg=vvv
- pu1=bbb
- pu2=ccc
- pw=kkk
- """
- p = {}
- file = open("C:/P32Working/Data/phone_book.txt")
- lines = file.readlines()
- for line in lines:
- key = line.partition('=')[0]
- value = line.partition('=')[2][:-1]
- p[key] = value
- def consolidate_keys_with_digits(keys_list):
- """
- Given a list of dictionary keys, returns a list identical to that list except that
- keys ending in a digit have that digit removed; any resulting duplicate keys are deleted;
- and the list is sorted.
- >>> keys_list
- [gp, mm1, mm2, er]
- >>> consolidate_keys_with_digits(keys_list)
- [er, mm, gp]
- """
- consolidated_keys_list = []
- for x in keys_list:
- if x[-1] in '0123456789':
- consolidated_keys_list.append(x[:-1])
- else:
- consolidated_keys_list.append(x)
- list_set = set(consolidated_keys_list)
- consolidated_keys_list = list(list_set)
- consolidated_keys_list.sort()
- return consolidated_keys_list
- while True:
- print()
- print("Enter initials of name, or 'all' to print phone book, or 'q' to quit.")
- try:
- initials = input("Enter: ").lower()
- print()
- if initials == 'q':
- print("Bye.")
- break
- elif initials == 'all':
- list_all = list(p.items())
- list_all.sort()
- for x in list_all:
- print(x)
- else:
- print(p[initials])
- except KeyError:
- keys_list = list(p.keys())
- consolidated_keys_list = consolidate_keys_with_digits(keys_list)
- initials_found_list = []
- for x in '0123456789':
- if (initials + x) in keys_list:
- initials_found_list.append(initials + x)
- if initials_found_list:
- for x in initials_found_list:
- print(p[x])
- elif initials == '':
- print("You didn't enter anything.")
- else:
- print("The initials '", initials, "' are not in phone book.", sep='')
- print("This is the list of entry initials:")
- print(consolidated_keys_list)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement