在字典中创建字典
creating a dictionary within a dictionary
我有一个名为播放列表的字典,以时间戳为键,以歌曲名称和艺术家为值,存储在一个元组中,格式如下:
{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')}
我正在尝试从此 dictionary/tuple 设置艺术家并将其设置为新字典中的键,值是该艺术家的歌曲及其在字典中出现的频率。示例输出为:
{'Chainsmokers': {'Closer': 3, 'Roses': 1},
'Elton John': {'Piano Man': 2}, … }
这是我到目前为止的代码:
dictionary = {}
for t in playlist.values():
if t[1] in dictionary:
artist_song[t[1]] += 1
else:
artist_songs[t[1]] = 1
print(dictionary)
不过,这只是returns艺人为key,艺人播放的频率为值。
在此先感谢您的帮助。
使用默认值为 defaultdict
的 defaultdict
,最后嵌套默认值为 int
:
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})}
非 defaultdict 方法有点冗长,因为我们需要确保字典存在,而这正是 defaultdict 为我们处理的。
d = {}
for song, artist in playlist.values():
d.setdefault(artist, {})
d[artist].setdefault(song, 0)
d[artist][song] += 1
只是为了好玩,这是一个使用 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
我有一个名为播放列表的字典,以时间戳为键,以歌曲名称和艺术家为值,存储在一个元组中,格式如下:
{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')}
我正在尝试从此 dictionary/tuple 设置艺术家并将其设置为新字典中的键,值是该艺术家的歌曲及其在字典中出现的频率。示例输出为:
{'Chainsmokers': {'Closer': 3, 'Roses': 1},
'Elton John': {'Piano Man': 2}, … }
这是我到目前为止的代码:
dictionary = {}
for t in playlist.values():
if t[1] in dictionary:
artist_song[t[1]] += 1
else:
artist_songs[t[1]] = 1
print(dictionary)
不过,这只是returns艺人为key,艺人播放的频率为值。
在此先感谢您的帮助。
使用默认值为 defaultdict
的 defaultdict
,最后嵌套默认值为 int
:
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})}
非 defaultdict 方法有点冗长,因为我们需要确保字典存在,而这正是 defaultdict 为我们处理的。
d = {}
for song, artist in playlist.values():
d.setdefault(artist, {})
d[artist].setdefault(song, 0)
d[artist][song] += 1
只是为了好玩,这是一个使用 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