""" Name: Prof. Xiannong Meng Course: CSCI 204 Lecture: 00 suggested solution for in-class coding exercise Based on the work by Professor Dancy """ def generate_names(): """Read user input for nick names and full names (separated by commas), store all of these names to a dictionary, and return this dictionary. Example sequence below: $python dictionary_sol.py >>Enter nicknames separated by commas: bb, cc, dd >>Enter full names separated by commas: bob barker, chris christie, donny darko >>bob barker or bb for short. >>chris christie or cc for short. >>donny darko or dd for short. """ n_names = input('Enter nicknames separated by commas : ') f_names = input('Enter full names separated by commas : ') dict = generate_dictionary(n_names, f_names) return dict def generate_dictionary(nick_names, full_names): """Generate a dictionary from the given strings of nick_names and full_names. Each name in the string is separated by a comma. Inputs: nick_names: A string of comma separated nicknames full_names: A string of comma separated full names that relate to the nicknames Output: a dictionary with the nicknames as keys and full names as values """ nn_list = nick_names.split(',') fn_list = full_names.split(',') all_names = {} #We didn't go over "assert", don't worry about it, but look it up if you # are interested assert len(nn_list) == len(fn_list), "Lists should be of equal length!" for i in range(len(nn_list)): nn_list[i] = nn_list[i].strip() fn_list[i] = fn_list[i].strip() all_names[nn_list[i]] = fn_list[i] return all_names def print_names(name_list): """Take the name_list as a dictionary, print its contents. Make use of the fact that name_list is a dictionary. Inputs: name_list: a dictionary 'key' is nick name, 'value' is full name Output: print the (nick name, full name) pair on the screen. """ for key in name_list.keys(): print(name_list[key] + ' or ' + key + ' for short.') ''' Alternatively, we could do the following ''' ''' keys = list(name_list.keys()) values = list(name_list.values()) for i in range(len(keys)): print(values[i] + ' or ' + keys[i] + ' for short.') ''' name_list = generate_names() print_names(name_list)