We'll work on a problem from a previous test:
Rolling Stone magazine published a list of the top 500 songs of all time
in 2004 and updated the list in 2010.A file stores the song, the artist,
and the year the song was released as shown below.
Like a Rolling Stone:Bob Dylan:1965
(I Can't Get No) Satisfaction:The Rolling Stones:1965
Imagine:John Lennon:1971
What's Going On:Marvin Gaye:1971
...
Born to Run:Bruce Springsteen:1975
Help!:The Beatles:1965
Write the function artists that returns a dictionary in
which the key is an artist (group, singer) and the corresponding value
is a list of the song titles from that artist. For example, both of
these entries would appear in the dictionary returned:
"The Beatles" : ["Hey Jude", "Yesterday", "I Want to Hold Your Hand", "Help!", ...]
"The Rolling Stones" : ["(I Can't Get No) Satisfaction", "Sympathy for the Devil", ...]
The parameter filename is the name of a file as shown above. Return the dictionary described.
def artists(filename):
"""
return dictionary in proper format given parameter
filename which has song information in proper format
"""
f = open(filename)
- Which of the loops below will set
line to be each line
of the file to be used in the body of the loop (more than one can be
correct).
-
for line in f:
-
for line in f.read():
-
for line in f.readlines()
- Which expression is the best choice for finding the artist/group name
on a line read from the file?
-
artist = line.split()[0]
-
artist = line[0]
-
artist = line.split(":")[0]
- Which expression is best to add a song title as part of the key in a
dictionary? Assume string variables
artist and song
have been properly initialized and that artist is a key in
dictionary d:
-
d[artist] = song
-
d[artist] = [song]
-
d[artist].append(song)