60.8k views
4 votes
PYTHONSorting 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.Ex: If the input is:file1.txtand the contents of file1.txt are:20Gunsmoke30The Simpsons10Will & Grace14Dallas20Law & Order12Murder, She Wrotethe file output_keys.txt should contain:10: Will & Grace12: Murder, She Wrote14: Dallas20: Gunsmoke; Law & Order30: The Simpsonsand the file output_titles.txt should contain:DallasGunsmokeLaw & OrderMurder, She WroteThe SimpsonsWill & Grace

User Szegedi
by
6.0k points

1 Answer

3 votes

Answer:

with open("file1.txt", "r") as file:

lines = file.readlines()

mydict = dict()

for x in range(0, len(lines) - 1, 2):

mydict[lines[x]] = lines[x-1]

dict_keys = sorted(mydict.keys)

sorted_dict ={}

for key in dict_keys:

sorted_dict[key] = mydict[key]

with open("output_keys.txt", "a+") as writn:

for key, value in sorted_dict.items():

writn.write(key: value)

writn.write("\\")

dict_values = sorted(mydict.values)

with open("output_titles", "a+") as title:

for name in dict_values:

title.write(name)

title.write("\\")

Step-by-step explanation:

The python program above reads in the file context, files.txt, and creates a dictionary of the file with the number of seasons as the key and movie title as the value. The sorted dictionary is saved in the output_keys.txt file and the titles in output_titles.txt file.

User Jigar Surana
by
5.5k points