【问题标题】:creating a dictionary within a dictionary在字典中创建字典
【发布时间】:2019-11-26 22:40:14
【问题描述】:

我有一个名为 playlist 的字典,其中时间戳作为键,歌曲标题和艺术家作为值,存储在一个元组中,格式如下:

{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')}

我正在尝试从此字典/元组中设置艺术家并将其设置为新字典中的键,值是该艺术家的歌曲以及它在字典中出现的频率。示例输出为:

{'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) 

但是,这只返回艺术家作为键和艺术家播放的频率作为值。

提前感谢您的帮助。

【问题讨论】:

  • 这段代码似曾相识,你最近在同一个程序上发过另一个问题吗?

标签: python dictionary python-3.6


【解决方案1】:

使用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 方法有点冗长,因为我们需要确保 dicts 存在,这是 defaultdict 为我们处理的。

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

【讨论】:

  • 谢谢!有没有一种方法可以在不需要导入 defaultdict 的情况下做到这一点?
  • @KyleTremblay 您可以手动进行检查 (if key in dict...)。
【解决方案2】:

只是为了好玩,这里有一个使用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

【讨论】:

    猜你喜欢
    • 2019-08-07
    • 2023-03-15
    • 1970-01-01
    • 2016-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-05
    相关资源
    最近更新 更多