Reputation: 1
song_lyrics_per_year={year:[(song, singer, lyrics),(song2, singer2, lyrics2)...], year2: ....}
Hello, I have a dict with year as keys and as values lists of tuples (consisting of song, singer, lyrics). No, I need to access all 3 elements separately and parse them into a list
onlysongs=[]
onlyartists=[]
However, all my tries have failed so far, including list comprehensions and codes that were suggested here.
Shouldn't this work?
for item in song_lyrics_per_year.values():
onlyartists.append(item[1])
In response, I get an "IndexError: list index out of range"
Only a few weeks into Python and I went through all old answers on this topic and tried the solutions...they did not work, unfortunately.
Thanks for your help!
Upvotes: 0
Views: 425
Reputation: 5372
I guess it would be clearer this way:
for year in song_lyrics_per_year:
for song_lyric in song_lyrics_per_year[year]:
song, singer, lyrics = song_lyric
if singer not in onlyartists:
onlyartists.append(singer)
Edited: to keep track of how often an artist appears you can use collections.Counter(). Here is a complete example:
from collections import Counter
singers = Counter()
years = {
2018: [
('Title1', 'Singer1', 'Lyrics1'),
('Title2', 'Singer1', 'Lyrics2')
],
2019: [
('Title3', 'Singer3', 'Lyrics3')
]
}
for year in years:
for song in years[year]:
title, singer, lyrics = song
singers.update((singer,))
for singer, hits in singers.most_common():
print(singer, hits)
And here is the output:
Singer1 2
Singer3 1
Upvotes: 0
Reputation: 773
for value in song_lyrics_per_year.values():
for i in range(0,len(value)-1):
onlysongs.append(value[i][0])
onlyartists.append(value[i][1])
Thanks for the edit @Austin.
Upvotes: 0
Reputation: 3037
I think you're missing 1 level of list. Try something like:
for songs_in_single_year in song_lyrics_per_year.values():
for song in songs_in_single_year:
onlyartists.append(song[1])
Upvotes: 1