我有一个名为播放列表的字典,其条目格式为:
{datetime.datetime(2019, 11, 4, 20, 2): ('Wagon Wheel', 'Darius Rucker'),
datetime.datetime(2019, 11, 4, 19, 59): ('Remember You Young', 'Thomas Rhett'),
datetime.datetime(2019, 11, 4, 19, 55): ('Long Hot Summer', 'Keith Urban')}
我想迭代这个字典来构造一个新的字典song_count,其中每首歌曲的名称作为键,其计数/频率作为值。这是到目前为止我所拥有的代码。
song_count = {}
for song in playlist:
if playlist[song] in song_count:
song_count[playlist[song]].append(song)
else:
song_count[playlist_[song]]=[song]
print(song_count)
但是,这无法将歌曲与调中的艺术家分开,也不会创建计数作为值。
新词典应如下所示:
{'Wagon Wheel-Darius Rucker': 1,
'Remember You Young-Thomas Rhett': 7,
'Long Hot Summer-Keith Urban': 1, … }
最佳答案
尝试对您的代码进行以下修改:
# Initialise new dictionary
song_count = dict()
# For each entry in the playlist dict
for song in playlist.values():
# Convert the tuple to song-artist string
song_name = '-'.join(song)
# If already in the dictionary, add 1 to the count
if song_name in song_count:
song_count[song_name] += 1
# Otherwise set the count to 1
else:
song_count[song_name] = 1
print(song_count)
输出:
{'Wagon Wheel-Darius Rucker': 1, 'Remember You Young-Thomas Rhett': 1, 'Long Hot Summer-Keith Urban': 1}
关于python - 从现有词典创建频率词典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59054498/