Kyle Tremblay
Kyle Tremblay

Reputation: 25

creating a dictionary within a dictionary

I have a dictionary called playlist with a timestamp as the key and song title and artist as the values, stored in a tuple, formatted as below:

{datetime.datetime(2019, 11, 4, 20, 2): ('Closer', 'The Chainsmokers'), 
datetime.datetime(2019, 11, 4, 19, 59): ('Piano Man', 'Elton John'), 
datetime.datetime(2019, 11, 4, 19, 55): ('Roses', 'The Chainsmokers')}

I am trying to set the artist from this dictionary/tuple and set it as the key in a new dictionary, with the values being songs by that artist and the frequency it occurs in the dictionary. Example output is:

{'Chainsmokers': {'Closer': 3, 'Roses': 1},
'Elton John': {'Piano Man': 2}, … }

This is what I have for code so far:

dictionary = {}
for t in playlist.values():
    if t[1] in dictionary:
        artist_song[t[1]] += 1
    else:
        artist_songs[t[1]] = 1
print(dictionary) 

However, this only returns the artist as the key and the frequency of artist plays as values.

Thanks in advance for any help.

Upvotes: 1

Views: 60

Answers (2)

Alex
Alex

Reputation: 7045

Use a defaultdict that has a defaultdict as it's default and finally has an int as nested default:

from collections import defaultdict

d = defaultdict(lambda: defaultdict(int))

for song, artist in playlist.values():
    d[artist][song] += 1

print(d)
# {'The Chainsmokers': {'Closer': 1, 'Roses': 1}), 'Elton John': {'Piano Man': 1})}

Non defaultdict method is a bit long-winded as we need to be sure that the dicts exist, which is what the defaultdict handles for us.

d = {}
for song, artist in playlist.values():
    d.setdefault(artist, {})
    d[artist].setdefault(song, 0)
    d[artist][song] += 1

Upvotes: 2

RishiG
RishiG

Reputation: 2830

Just for fun, here's an alternative version that makes use of collections.Counter:

from collections import defaultdict, Counter

song_count = defaultdict(dict)
for (song, artist), count in Counter(playlist.values()).items():
    song_count[artist][song] = count

Upvotes: 1

Related Questions