
Concept explainers
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.
Ex: If the input is:
file1.txt
and the contents of file1.txt are:
20 Gunsmoke 30 The Simpsons 10 Will & Grace 14 Dallas 20 Law & Order 12 Murder, She Wrote
the file output_keys.txt should contain:
10: Will & Grace 12: Murder, She Wrote 14: Dallas 20: Gunsmoke; Law & Order 30: The Simpsons
and the file output_titles.txt should contain:
Dallas Gunsmoke Law & Order Murder, She Wrote The Simpsons Will & Grace
Note: There is a newline at the end of each output file.
**Code**
def readFile(file_Name):
dictn = {}
with open(file_Name, 'r') as inp_File:
lines = inp_File.readlines()
for index in range(0, len(lines) - 1, 2):
if lines[index].strip()=='':continue
cnt = int(lines[index].strip())
name = lines[index + 1].strip()
if cnt in dictn.keys():
name_list = dictn.get(cnt)
name_list.append(name)
name_list.sort()
else:
dictn[cnt] = [name]
print(cnt,name)
return dictn
def output_keys(dictn, file_Name):
with open(file_Name,'w+') as out_File:
for key in sorted(dictn.keys()):
out_File.write('{}: {}\n'.format(key,';'.join(dictn.get(key))))
print('{}: {}\n'.format(key,';'.join(dictn.get(key))))
def output_titles(dictn, file_Name):
titles = []
for title in dictn.values():
titles.extend(title)
with open(file_Name,'w+') as out_File:
for title in sorted(titles):
out_File.write('{}\n'.format(title))
print(title)
def main():
file_Name = input()
dictn = readFile(file_Name)
if dictn is None:
print('Error: Invalid file name provided: {}'.format(file_Name))
return
print(dictn)
output_file_Name_1 ='output_keys.txt'
output_file_Name_2 ='output_titles.txt'
output_keys(dictn,output_file_Name_1)
output_titles(dictn,output_file_Name_2)
main()
**The output for this code has an extra line and some extra spacing that I dont need. Output is below.
20 Gunsmoke
30 The Simpsons
10 Will & Grace
14 Dallas
20 Law & Order
12 Murder, She Wrote
{20: ['Gunsmoke', 'Law & Order'], 30: ['The Simpsons'], 10: ['Will & Grace'], 14: ['Dallas'], 12: ['Murder, She Wrote']} **This is not needed**
10: Will & Grace
12: Murder, She Wrote
14: Dallas
20: Gunsmoke;Law & Order
30: The Simpsons *** this section and up to the last section "not needed" has to many spaces**
Dallas
Gunsmoke
Law & Order
Murder, She Wrote
The Simpsons
Will & Grace

Trending nowThis is a popular solution!
Step by stepSolved in 6 steps with 5 images

- Read strings from input until 'stop' is read. For each string read: If the string is a key in dictionary patients_record, delete the key from patients_record and output the string followed by ' deleted'. Otherwise, output the string followed by ' not a key'.arrow_forwardPlease complete on Python Write a program that keeps a dictionary in which both keys and values are strings, names of students and their courses grades. Prompt the user of the program to add or remove students, to modify grades, or to print all grades. The printout should be sorted by name and formatted like this: <br>Carl: B+ <br>Joe: C <br>Sarah: A <br>Francine: Aarrow_forwardWrite a python program that creates a dictionary containing the U.S. states as keys, and their capitals as values. The program should then randomly quiz the user by displaying the name of a state and asking the user to enter that state's capital. The program should keep a count of the number of correct and incorrect responses. This program has really been giving me trouble. Any help is greatly appreciated. Thanks so much!arrow_forward
- How can I read from a file a string version of a nested dictionary and store as a dictionary? For example, I have the following nested dictionary: {1: {'Name': 'Bob', 'Pass': 'pass123', 'Sports': ['Hockey', 'Football'], 'Activities': ['eating', 'sleeping']} ; 2: {'Name': 'Kayla', 'Pass': 'cyansus', 'Sports': [], 'Activities': []}} To write this to a file I needed to convert to a string (and it is fine writing to a file). But I am having trouble reading this from the file and creating a nested dictionary from it. I can read the string in fine but creating the nested dictionary I am lost at. Any help will be appreciated. Thank youarrow_forwardWrite a python program that reads the contents of a text file. The program should create a dictionary in which the keys are the individual words found in the file and the values are the number of times each word appears. For example, if the word "the" appears 128 times, the dictionary would contain an element with 'the' as the key and 128 as the value. The program should either display the frequency of each word or create a second file containing a list of each word and it's frequency. This program has really been giving me trouble. Any help is great appreciated. Thanks so much!arrow_forwardPYTHON QUESTION This assignment requires you to create a dictionary by reading the text file created for the Chapter 6 assignment. The dictionary should have player names for the keys. The value for each key must be a two-element list holding the player's goals and assists, respectively. See page 472! Start with an empty dictionary. Then, use a loop to cycle through the text file and add key-value pairs to the dictionary. Close the text file and process the dictionary to print the stats and determine the top scorer as before. In fact, much of the code used in program6_2.py can be copied and used for this program. Printing the stats for each player is the most challenging part of this program. To master this, refer to the examples in the zip file that can be downloaded from the "Dictionary values can be lists" link in the "Learn Here" part of this module. NOTE: you do not need to submit the text file. Submit just this program. The required output should be the same well-formatted table…arrow_forward
- In Python languagearrow_forwardPlease write a program using python that will create a dictionary and keep count of how many words of certain length are seen in a known text file. For example, in text file "example.txt" there are 5 words; chocolate, mild, separate, question, and. This would produce: {8:2, 9:1, 4:1, 3:1}arrow_forwardThis code is full of errors, what are 4 of them and how I would fix them?arrow_forward
- In python: student_dict is a dictionary with students' name and pedometer reading pairs. A new student is read from input and added into student_dict. For each student in student_dict, output the student's name, followed by "'s pedometer reading: ", and the student's pedometer reading. Then, assign average_value with the average of all the pedometer readings in student_dict..arrow_forwardIn Python, create a telephone dictionary where the user is asked whether they wish to add, remove,modify, search for a telephone number (given the name), or exit. Use functions for each one ofthe four different operations. Use an infinite looparrow_forwardWrite a python program that stores current grades in a dictionary, with course codes as keys and percent grades as values. Start with an empty dictionary and then use a while loop to enable input of course codes and percent grades from the keyboard. Enter data for at least five courses. After entering the data, use a for loop and the keys to show the current status of all courses. This same loop should include code that enables determination of the worst course and the average of all courses. Both of these findings should be printed when the loop ends. The worst course should be dropped and reported. This being done, the program should use another loop and the items method to display the revised courses and grades and report the revised term average.arrow_forward
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education





