pythonoutputspacing

Removing added spacing from join statement


I have been tasked with 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. 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

I have typed out this code:

user_input = input()

with open(user_input, 'r') as f:
    lines = f.readlines()
    
shows = {}
for i in range(0, len(lines), 2):
    seasons = int(lines[i])
    show = lines[i + 1]
    if seasons not in shows:
        shows[seasons] = []
    shows[seasons].append(show)

with open('output_keys.txt', 'w') as f:
    for seasons in sorted(shows.keys()):
        f.write(f'{seasons}: {"; ".join(sorted(shows[seasons]))}')

with open('output_titles.txt', 'w') as f:
    titles = []
    for show_list in shows.values():
        titles.extend(show_list)
    for title in sorted(titles):
        f.write(f'{title}')

The issue lies in the output of the file. This code outputs:

10: Will & Grace
12: Murder, She Wrote
14: Dallas
20: Gunsmoke
; Law & Order
30: The Simpsons

When I want it to output:

10: Will & Grace
12: Murder, She Wrote
14: Dallas
20: Gunsmoke; Law & Order
30: The Simpsons

Solution

  • Here is and example how you could read the file into a dictionary, sort it and write it to the output file:

    with open("your_file.txt", "r") as f_in:
        keys, values, cnt = [], [], 0
        for line in map(str.strip, f_in):
            if line == "":
                continue
            (values if cnt % 2 else keys).append(line)
            cnt += 1
    
    out = {}
    for k, v in zip(keys, values):
        out.setdefault(int(k), []).append(v)
    
    print(out)
    

    This creates dictionary out with contents:

    {
        20: ["Gunsmoke", "Law & Order"],
        30: ["The Simpsons"],
        10: ["Will & Grace"],
        14: ["Dallas"],
        12: ["Murder, She Wrote"],
    }
    

    Then you can sort the keys and write it to the output file:

    with open("your_output.txt", "w") as f_out:
        for k, v in sorted(out.items()):
            print(f'{k}: {"; ".join(v)}', file=f_out)
    

    Creates your_output.txt:

    10: Will & Grace
    12: Murder, She Wrote
    14: Dallas
    20: Gunsmoke; Law & Order
    30: The Simpsons