Question

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 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.

My current code:

def readFile(filename):
dict = {}
with open(filename, 'r') as infile:
lines = infile.readlines()
for index in range(0, len(lines) - 1, 2):
if lines[index].strip()=='':continue
count = int(lines[index].strip())
name = lines[index + 1].strip()
if count in dict.keys():
name_list = dict.get(count)
name_list.append(name)
name_list.sort()
else:
dict[count] = [name]
print(count,name)


return dict


def output_keys(dict, filename):
with open(filename,'w+') as outfile:
for key in sorted(dict.keys()):
outfile.write('{}: {}\n'.format(key,'; '.join(dict.get(key))))
print('{}: {}\n'.format(key,';'.join(dict.get(key))))


def output_titles(dict, filename):
titles = []
for title in dict.values():
titles.extend(title)
with open(filename,'w+') as outfile:

for title in sorted(titles):
outfile.write('{}\n'.format(title))
print(title)


def main():
filename = input('Enter input file name: ')
dict = readFile(filename)
if dict is None:
print('Error: Invalid file name provided: {}'.format(filename))
return
print(dict)
output_filename_1 ='output_keys.txt'
output_filename_2 ='output_titles.txt'

output_keys(dict,output_filename_1)
output_titles(dict,output_filename_2)


main()

output from my incorrect code:

ל-צדד.חייו: אמנם יורים: מ:Ice הבא:. ד. : באה: מבנןו ;:בזה שין- - - י י 1 441 : . --! אין -*י* אי י י - - - ין ני די. 3 הי

Better screen shot of image results
https://i.ibb.co/hcjT5rd/code-results.png

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

def readFile(filename):

dic = {}

try:

with open(filename,'r') as infile:

lines = infile.readlines()

for li in lines:

key,value =li.strip().split(maxsplit=1)

if int(key) in dic:

dic[int(key)].append(value)

else:

dic[int(key)]=[value]

except:

return None

return dic

def process(dec):

temp1 = {}

temp2 = {}

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

temp1[key]=list(set(dec[key]))

temp2[key]=sorted(list(set(dec[key])))

ans1 = ""

ans2 = ""

for key,value in temp1.items():

ans1+=str(key)+': '+'; '.join(value)+'\n'

for key,value in temp2.items():

ans2+=str(key)+': '+'; '.join(value)+'\n'

return ans1[:-1],ans2[:-1]

def writeFile(ans,filename):

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

outfile.write(ans)

def main():

filename = input('Enter input file name: ')

dic = readFile(filename)

if dic is None:

print('Error: Invalid file name povided: {}'.format(filename))

return

output_filename_1 ='output_keys.txt'

output_filename_2 ='output_titles.txt'

ans1,ans2 = process(dic)

writeFile(ans1,output_filename_1)

writeFile(ans2,output_filename_2)

main()

 def readFile(filename): dic = {} try: with open(filename,'r') as infile: lines = infile.readlines() for li in lines: key,value =li.strip().split(maxsplit=1) if int(key) in dic: dic[int(key)].append(value) else: dic[int(key)]=[value] except: return None return dic def process(dec): temp1 = {} temp2 = {} for key in sorted(dec.keys()): temp1[key]=list(set(dec[key])) temp2[key]=sorted(list(set(dec[key]))) ans1 = "" ans2 = "" for key,value in temp1.items(): ans1+=str(key)+': '+'; '.join(value)+'\n' for key,value in temp2.items(): ans2+=str(key)+': '+'; '.join(value)+'\n' return ans1[:-1],ans2[:-1] def writeFile(ans,filename): with open(filename,'w') as outfile: outfile.write(ans) def main(): filename = input('Enter input file name: ') dic = readFile(filename) if dic is None: print('Error: Invalid file name povided: {}'.format(filename)) return output_filename_1 ='output_keys.txt' output_filename_2 ='output_titles.txt' ans1,ans2 = process(dic) writeFile(ans1,output_filename_1) writeFile(ans2,output_filename_2) main()

Add a comment
Know the answer?
Add Answer to:
Python 12.10 LAB: Sorting TV Shows (dictionaries and lists) Write a program that first reads in...
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
  • 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...

  • In python, PART A: I am trying to get a dictionary with size(4, 5, 6) as...

    In python, PART A: I am trying to get a dictionary with size(4, 5, 6) as keys and an array for key containing a list of values (words from file of respective size) associated with those keys I am reading from a file of strings, where I am only interested with words of length 4, 5, and 6 to compute my program reading the text file line by line: At first, I have an empty dictionary then to that I...

  • Write a function named "loadStateDict(filename) that takes a filename and returns a dictionary of 2-character state...

    Write a function named "loadStateDict(filename) that takes a filename and returns a dictionary of 2-character state codes and state names. The file has four columns and they are separated by commas. The first column is the state full name and the second column is the state code. You don't have to worry about column 3 & 4. You should eliminate any row that is without a state code. Save the two columns into a dictionary with key = state code...

  • Python Modify your recommendation program so that it reports the titles of the works rather than their file names. To do...

    Python Modify your recommendation program so that it reports the titles of the works rather than their file names. To do this, write a program that reads in the titles.txt file and creates a dictionary that looks up the title using the file name. This dictionary should then be used to report the works by their title instead of their file name. Script to use: import os import math def count_word(table, word): 'for the word entry in the table, increment...

  • Consider python please for this problem: I did a python program to read the first 20 lines from a...

    Consider python please for this problem: I did a python program to read the first 20 lines from a file and here is the code holder = 20 lines = 3 file = "123456.pssm" _file = ".txt" while 1:         out_file = input("[OUTPUT] - Please enter the name of file: ") + _file         if (not _file):         print("Filename not specified - Please Try Again\n")         continue     break with open(_file, "a") as e:     with open(file, "r") as f:         for num, line in enumerate(f, 1):                        ...

  • 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...

  • Python 3 Modify the sentence-generator program of Case Study so that it inputs its vocabulary from...

    Python 3 Modify the sentence-generator program of Case Study so that it inputs its vocabulary from a set of text files at startup. The filenames are nouns.txt, verbs. txt, articles.txt, and prepositions.txt. (HINT: Define a single new function, getWords. This function should expect a filename as an argument. The function should open an input file with this name, define a temporary list, read words from the file, and add them to the list. The function should then convert the list...

  • Modify your program from Learning Journal Unit 7 to read dictionary items from a file and write the inverted dictionary to a file. You will need to decide on the following:

    Modify your program from Learning Journal Unit 7 to read dictionary items from a file and write the inverted dictionary to a file. You will need to decide on the following:How to format each dictionary item as a text string in the input file.How to covert each input string into a dictionary item.How to format each item of your inverted dictionary as a text string in the output file.Create an input file with your original three-or-more items and add at...

  • I need this python program to access an excel file, books inventory file. The file called...

    I need this python program to access an excel file, books inventory file. The file called (bkstr_inv.xlsx), and I need to add another option [search books], option to allow a customer to search the books inventory, please. CODE ''' Shows the menu with options and gets the user selection. ''' def GetOptionFromUser(): print("******************BookStore**************************") print("1. Add Books") print("2. View Books") print("3. Add To Cart") print("4. View Receipt") print("5. Buy Books") print("6. Clear Cart") print("7. Exit") print("*****************************************************") option = int(input("Select your option:...

  • 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