How to solve an error with improper alphabetical comparison

1.2k Views Asked by At

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

What should I do to solve this specifically? enter image description here

3

There are 3 best solutions below

1
On

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

with open(titlesFilename, 'w') as titlesFile:        
    for show in sorted(sum(shows.values(), []):        
        titlesFile.write(show + "\n")

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 use itertools.chain or al good comprehension sorted((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

0
On

The problem here is that shows.values() iterates over lists, not strings, so the sort doesn't quite work as you'd like. You could amalgamate these to a single list, but equally you could retain that list of show names in the first place as you read them in; so your initial interpretation loop would become:

allshows = []    # also collect just names
for i in range(record_count):
    seasons = int(showData[2 * i].strip())
    showName = showData[2 * i + 1].strip()
    allshows.append(showName)    # collect for later output

    if seasons in shows:
        shows[seasons].append(showName)
    else:
        shows[seasons] = [showName]

allshows.sort()    # ready for output

and then output would be a simple iteration over this extra list.

0
On

This is the correct code for any future inquiries. I'm currently taking IT-140 and this passed all tests. If you follow the pseudocode line for line in the module videos, you'll easily get this.

file_name = input()
user_file = open(str(file_name))
output_list = user_file.readlines()
my_dict = {}
show_list = []
show_list_split = []
for i in range(len(output_list)):
    temp_list = []
    list_object = output_list[i].strip('\n')
    if (i + 1 < len(output_list) and (i % 2 == 0)):
        if int(list_object) in my_dict:
            my_dict[int(list_object)].append(output_list[i + 1].strip('\n'))
        else:
            temp_list.append(output_list[i + 1].strip('\n'))
            my_dict[int(list_object)] = temp_list
            
my_dict_sorted_by_keys = dict(sorted(my_dict.items()))
for x in my_dict.keys():
    show_list.append(my_dict[x])
for x in show_list:
    for i in x:
        show_list_split.append(i)
show_list_split = sorted(show_list_split)
f = open('output_keys.txt', 'w')
for key, value in my_dict_sorted_by_keys.items():
    f.write(str(key) + ': ')
    for item in value[:-1]:
        f.write(item + '; ')
    else:
        f.write(value[-1])
        f.write('\n')
        
f.close()
f = open('output_titles.txt', 'w')
for item in show_list_split:
    f.write(item + '\n')
f.close()