diff --git a/7/7.9 LAB/file1.txt b/7/7.9 LAB/file1.txt new file mode 100644 index 0000000..c65c870 --- /dev/null +++ b/7/7.9 LAB/file1.txt @@ -0,0 +1,12 @@ +20 +Gunsmoke +30 +The Simpsons +10 +Will & Grace +14 +Dallas +20 +Law & Order +12 +Murder, She Wrote diff --git a/7/7.9 LAB/main.py b/7/7.9 LAB/main.py new file mode 100644 index 0000000..a69aec1 --- /dev/null +++ b/7/7.9 LAB/main.py @@ -0,0 +1,61 @@ +class MutliKeyDict(dict): + """ + New Multi Key dict for this application, inherits 'dict' + """ + def __setitem__(self, key, value): # Overwrites the default __setitem__ + try: + self[key] + except KeyError: # If there is a key error (like we append the same season num twice) + super(MutliKeyDict, self).__setitem__(key, []) # Make that value a list insted, + self[key].append(value) # Append that new list and save + +def pharse_shows(file_location): + result = MutliKeyDict() + try: + with open(file_location) as f: + for line in f: + season = line.strip("\n") + title = next(f).strip("\n") + result[season] = title + except StopIteration: + print('Error pharsing last value, odd number of lines in file?') + return(result) + +def save_output_keys(showdict): + result = '' # Set the result to a blank string + showdict = dict(sorted(showdict.items())) # Sort the dict by key + + for entry in showdict: # For every dict entry in our show dict + result += '{0}: '.format(entry) # Append a new line to represent that entry season count + if isinstance(showdict[entry], list): # If the entry is a list of shows + for show in showdict[entry]: # for very entry in that list of shows + result += '{0}; '.format(show) # append that show, and a ";" + result = result[:-2] + '\n' # Chop the last ";", ugly but it works. Also add carriage return + else: # If the entry is not a list + result += '{0}'.format(showdict[entry]) + + with open('output_keys.txt', 'a') as f: + f.write(result) + +def save_output_titles(showdict): + result = [] # Set the result to a blank list + for entry in showdict: # For every dict entry in our show dict + if isinstance(showdict[entry], list): # If the entry is a list of shows + for show in showdict[entry]: # for every entry in that list of shows + result.append(show) # Append that show to our result list + else: # If the entry is not a list + result.append(showdict[entry]) # Append the result directly + + result.sort() # Sort the list + + resultstring = '' # Setup a new blank result string + for item in result: # Convert list to stirng, with \n + resultstring += str(item) + '\n' + + with open('output_titles.txt', 'a') as f: + f.write(resultstring) + +if __name__ == '__main__': + showdict = pharse_shows(input()) + save_output_keys(showdict) + save_output_titles(showdict)