【发布时间】:2019-11-26 15:41:59
【问题描述】:
我有一本名为 playlist 的字典,其条目形式为:
{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, … }
【问题讨论】:
标签: python python-3.x dictionary count python-datetime