Answer to Question #340908 in Python for CACA ROcka

Question #340908


Write a program that first reads in the name of an input file and then reads the input file using the file.readlines() method. The input file contains an unsorted list of number of seasons followed by the corresponding TV show. Your program should put the contents of the input file into a dictionary where the number of seasons are the keys, and a list of TV shows are the values (since multiple shows could have the same number of seasons).

Sort the dictionary by key (least to greatest) and output the results to a file named output_keys.txt. Separate multiple TV shows associated with the same key with a semicolon (;), ordering by appearance in the input file. Next, sort the dictionary by values (alphabetical order), and output the results to a file named output_titles.txt.


1
Expert's answer
2022-05-17T06:02:01-0400

def read_da_file(file):

        dict1 = {}

        with open(file, 'r',encoding='utf-8') as infile:

            lines = infile.readlines()

            for index in range(0, len(lines) - 1, 2):

                if lines[index].strip() == '':

                    continue

                count = int(lines[index].strip())

                show = lines[index + 1].strip()

                if count in dict1.keys():

                    show_list = dict1.get(count)

                    show_list.append(show)

                else:

                    dict1[count] = [show]


        return dict1



def output_keys(dict1, filename):

        with open(filename, 'w+') as q:

            for key in sorted(dict1.keys()):

                q.write('{}: {}\n'.format(key, '; '.join(dict1.get(key))))


                print('{}: {}'.format(key, '; '.join(dict1.get(key))))



def output_titles(dict1, filename):

        titles = []


        for title in dict1.values():

            titles.extend(title)


        with open(filename, 'w+') as outfile:


            for title in sorted(titles):

                outfile.write('{}\n'.format(title))

                print(title)



def main(x):

        file_name = x

        dict1 = read_da_file(file_name)

        if dict1 is None:

            print('Error: Invalid file name provided: {}'.format(file_name))


            return

        output_filename_1 = 'output_keys.txt'

        output_filename_2 = 'output_titles.txt'

        output_keys(dict1, output_filename_1)

        output_titles(dict1, output_filename_2)



user_input = input()

main(user_input)


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS