I have to 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. Program puts 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). Sorts 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 (;). Sorts the dictionary by values (alphabetical order), and outputs the results to a file named output_titles.txt. So if my input file is "file1.txt" and the contents of that file 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_title.txt contains:
Dallas
Gunsmoke
Law & Order
Murder, She Wrote
The Simpsons
Will & Grace
My code works perfectly fine and my assignment grades it fine except for the part with the "output_titles.txt" What I wrote in code doesn't put it in alphabetical order for it and I don't know where to go from here. My code is:
inputFilename = input()
keysFilename = 'output_keys.txt'
titlesFilename = 'output_titles.txt'
shows = {}
with open(inputFilename) as inputFile:
showData = inputFile.readlines()
record_count = int(len(showData) / 2)
for i in range(record_count):
seasons = int(showData[2 * i].strip())
showName = showData[2 * i + 1].strip()
if seasons in shows:
shows[seasons].append(showName)
else:
shows[seasons] = [showName]
with open(keysFilename, 'w') as keysFile:
for season in sorted(shows):
keysFile.write(str(season) + ': ')
keysFile.write('; '.join(shows[season]) + '\n')
with open(titlesFilename, 'w') as titlesFile:
for show_list in sorted(shows.values()):
for show in show_list:
titlesFile.write(show + "\n")
I've attached a picture of the problem I get notified of:1
That because you sorted a list of string lists. Each sublist corresponds to a different number of shows, and sorting the big lists, does not sort sublists. Just make one big plain list of show names and sort it. Try, for instance
I used the
sum
since it is succinct and intuitive, yet it might be a terribly slow considering amount of tv programming today. For greatest efficiency useitertools.chain
or al good comprehensionsorted((show for show_titles in shows for show in show_titles.values()))
. Iterating over the list of list was discussed before many times, e.g. Concatenation of many lists in Python pick any method you like