python - 从现有词典创建频率词典

标签 python python-3.x dictionary count python-datetime

我有一个名为播放列表的字典,其条目格式为:

{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/

相关文章:

python 单词中字母的位置频率字典

python - for循环内递增变量

Python3 Typeerror : replace() argument 1 must be str, 不是 int

python-3.x - 如何遍历电子邮件及其附件 Python win32

ios - 如何从 IOS Swift 'Any' 类型访问和获取嵌套值?

python - 在wxpython中导入并显示.txt文件

python - 修复 Python 的 Pg 中的类型错误

qlabel 中的 python 错误 : can not show . gif

dictionary - Swift - map 注释的更好方法

python - OrderedDict 如何知道已经实例化的字典的元素顺序?