Question

7.10 LAB: Sorting TV Shows (dictionaries and lists)

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, separating multiple TV shows associated with the same key with a semicolon (;). Next, sort the dictionary by values (alphabetical order), and output the results to a file named output_titles.txt.


This is my current code but it doesn't produce any output. I need help with it.


# Type your code here


def file_reader(file_name):

    tv_dict = {}

    try:

        with open(file_name,"r") as myfile:

            details = myfile.readlines()

            for item in details:

                k,v =item.strip().split(maxsplit=1)

                if int(k) in tv_dict:

                    tv_dict[int(k)].append(v)

                else:

                    tv_dict[int(k)]=[v]

    except:

        return None

    return tv_dict

    

def sorting(dict_t):

    sort1 = {}

    sort2 = {}

    for k in sorted(dict_t.keys()):

        sort1[k]=list(set(dict_t[k]))

        sort2[k]=sorted(list(set(dict_t[k])))

    out1 = ""

    out2 = ""

    for k,v in sort1.items():

        out1+=str(k)+": "+"; ".join(v)+"\n"

    for key,value in sort2.items():

        out2+=str(k)+": "+"; ".join(v)+"\n"

    return out1[:-1],out2[:-1]


def output_file(output,filename):

    with open(filename,"w") as outfile:

        outfile.write(output)


def main():

    input_file = input("Enter input file name:")

    tv_dict = file_reader(input_file)

    if tv_dict is None:

        print("Error: File Not Found: {}".format(input_file))

        return

    output_file1 ="output_keys.txt"

    output_file2 ="output_titles.txt"

    out1,out2 = sorting(tv_dict)

    output_file(out1, output_file1)

    output_file(out2, output_file2)

main()


0 0
Add a comment Improve this question Transcribed image text
Answer #1

def readInputFile(filename):

   shows_dict = {}                                   #create an empty dictionary

   infile = open(filename, 'r')                   #open input file

   lines = infile.readlines()                       #read all lines of the file

   for i in range(0, len(lines), 2):               #loop for all lines, with increment of 2

       numOfSeasons = int(lines[i].strip())       #get number of seasons from ith line

       show = lines[i+1].strip()                   #get show name from (i+1)th line

       if numOfSeasons not in shows_dict.keys():   #create a key for numOfSeasons if it not exists

           shows_dict[numOfSeasons] = []

       shows_dict[numOfSeasons].append(show)        #add the show to the list of values for that key

   #print(shows_dict)  

   return shows_dict                               #return the dictionary



def outputSortedbyKeys(dict, filename):

   print("Sorting by keys: ")

   outfile = open(filename,'w')                   #open output file for writing

   for key in sorted(dict.keys()):                   #sort the keys

       outfile.write('{}: {}\n'.format(key,'; '.join(dict.get(key))))   #write the key: values separated by ;

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

   print(filename + " written successfully\n")



def outputSortedbyValues(dict, filename):

   titles = []

   for key in dict.keys():                           #get all the values and store in titles list

       for val in dict[key]:

           titles.append(val)

   outfile = open(filename,'w')                   #open output file for writing

   for title in sorted(titles):                   #sort the titles list and write to file

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

       print(title)

   print(filename + " written successfully\n")


def main():

   filename = input("Enter the input filename: ")       #read name of inputfile

   shows_dict = readInputFile(filename)               #read data from file and get the dictionary

   outputSortedbyKeys(shows_dict , 'output_keys.txt')   #sort and output dictionary sorted by keys

   outputSortedbyValues(shows_dict , 'output_titles.txt') #sort and output dictionary sorted by values


main()


answered by: codegates
Add a comment
Know the answer?
Add Answer to:
7.10 LAB: Sorting TV Shows (dictionaries and lists)
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Python 12.10 LAB: Sorting TV Shows (dictionaries and lists) Write a program that first reads in...

    Python 12.10 LAB: Sorting TV Shows (dictionaries and lists) 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...

  • please complete the missing function only to figure out how many numbers fall within the range...

    please complete the missing function only to figure out how many numbers fall within the range of 90 through 99 total of 29 values in C 6 finclude "lab5.h" 8 const char *FILENAME() - / array of the data file names * ("lab5a.dat", "lab5b.dat", NULL); 12 int main(void) 13 int file count = 0; keeps track of which file we are on/ int check overflow - 0; / counter to prevent array overflow int real filesize = 0; /actual count...

  • Python problem. 3. (6 pts) Define the following four sorting functions: each takes an argument that...

    Python problem. 3. (6 pts) Define the following four sorting functions: each takes an argument that is a list of int or str or both values (otherwise raise an AssertionError exception with an appropriate error message) that will be sorted in a different way. Your function bodies must contain exactly one assert statement followed by one return statement. In parts a-c, create no other extra/temporary lists other than the ones returned by calling sorted. a. (2 pts) Define the mixed...

  • I have a multithreaded java sorting program that works as follows: 1. A list of double...

    I have a multithreaded java sorting program that works as follows: 1. A list of double values is divided into two smaller lists of equal size 2. Two separate threads (which we will term sorting threads) sort each sublist using a sorting algorithm of your choice 3. The two sublists are then merged by a third thread merging thread that merges the two sublists into a single sorted list. SIMPLE EXECUTION >java SortParallel 1000 Sorting is done in 8.172561ms when...

  • I'm trying to sort a list of students from a text file in python(3.7) with three separate sorting functions (Bubble, selection, insert) I'm not sure to why as its not working I'm going to...

    I'm trying to sort a list of students from a text file in python(3.7) with three separate sorting functions (Bubble, selection, insert) I'm not sure to why as its not working I'm going to guess its because I'm not using the swap function I built. Every time I run it though I get an error that says the following Traceback (most recent call last): File "C:/Users/tkoto/Desktop/SearchAndSortLab.py", line 146, in <module> main() File "C:/Users/tkoto/Desktop/SearchAndSortLab.py", line 122, in main studentArray.gpaSort() File "C:/Users/tkoto/Desktop/SearchAndSortLab.py",...

  • can someone please help me write a python code for this urgently, asap Question: Write a Python function, minmp,...

    can someone please help me write a python code for this urgently, asap Question: Write a Python function, minmp, that is passed a file name and a metal alloy's formula unit structure*". The file will contain metal elements and their properties. The function will return a tuple of the element from the formula with the lowest melting point and that melting point Write a second function, molform, that will be called by the first function, to take the metal alloy's...

  • QUESTION The ReadFile class opens and reads a text file. The WriteFile class opens and writes...

    QUESTION The ReadFile class opens and reads a text file. The WriteFile class opens and writes to a file. Compile and run these programs. There are several ways to read/write text files. The examples shown here are just one way of achieving this. Look at the API for the BufferedReader class. The readline() method is a simple way to read the text file line by line. It returns null when the end of the file has been reached. https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html Look...

  • PYTHON The provided code in the ATM program is incomplete. Complete the run method of the...

    PYTHON The provided code in the ATM program is incomplete. Complete the run method of the ATM class. The program should display a message that the police will be called after a user has had three successive failures. The program should also shut down the bank when this happens. [comment]: <> (The ATM program allows a user an indefinite number of attempts to log in. Fix the program so that it displays a message that the police will be called...

  • Hey I have a task which consists of two part. Part A asks for writing a...

    Hey I have a task which consists of two part. Part A asks for writing a program of WORD & LINE CONCORDANCE APPLICATION in python which I have completed it. Now the second part has given 5 dictionary implementation codes namely as: (ChainingDict, OpenAddrHashDict with linear probing, OpenAddrHashDict with quadratic probing, and 2 tree-based dictionaries from lab 12 (BST-based dictionary implementation) and asks for my above program WORD & LINE CONCORDANCE APPLICATION  to use these implemented code and show the time...

  • NOTE: LANGUAGE IS PYTHON CS160 Computer Science Lab 17 Objectives Work with dictionaries Work with functions...

    NOTE: LANGUAGE IS PYTHON CS160 Computer Science Lab 17 Objectives Work with dictionaries Work with functions Work with files Overview This lab will have you store the birthdays for a group of people. This program will store the information with the focus on the date of the month and not on the individual. The point of this program is to be able to see who has a birthday on a given day or to create a table of birthdays, in...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT