Python - 在词典中查找热门项目

时间:2016-11-30 00:07:09

标签: python dictionary

我想在下面的逐项数据结构中检索top track

tracks = {
u'Harry Patch (In Memory Of)': {u'playlist1': 4.0}, 
u'Fake Plastic Trees': {u'playlist2': 5.0, u'playlist1': 6.0}, 
u'The Man Who Sold The World': {u'playlist1': 3.0}, 
u'Running Up That Hill': {u'playlist1': 2.0}, 
u"Jeep's Blues": {u'playlist3': 1.0, u'playlist4':9.0}, 
u'Stella By Starlight': {u'playlist3': 1.0}, 
u'Codex': {u'playlist1': 3.0}
}

逻辑如下:

1 - 找到属于多个播放列表的曲目。

2 - 在这些结果中,找到此曲目的最高排名。 (添加个别播放列表排名)

我在这个片段中部分存在:

tracks = [i[0] for i in radio.items()]
playlists = [i[1] for i in radio.items()]

ranking = []

for p in playlists:
    name = p.keys()
    rank = p.values()
    if len(rank) >= 2:  
        ranks = sum(r for r in rank)
        ranking.append(ranks)

print max(ranking)

打印:11.0,对应于所需的输出u'Fake Plastic Trees

但是我已经失去了track name的跟踪(原谅我的双关语)。

如何使用上面的代码检索曲目名称?

PS。有没有更简单的方法来实现我想要的结果?

3 个答案:

答案 0 :(得分:2)

默认情况下,在使用for循环时仅迭代dict的值。您也可以使用iteritems()

获取密钥
tracks = [i[0] for i in radio.items()]
playlists = [i[1] for i in radio.items()]

ranking = []
songs = []

for song, p in playlists.iteritems():
    name = p.keys()
    rank = p.values()
    if len(rank) >= 2:  
        ranks = sum(r for r in rank)
        ranking.append(ranks)
        songs.append(song)

import numpy as np
song_index = np.argmax(ranking)
print songs[song_index]

答案 1 :(得分:1)

虽然@Tim解决了代码的工作原理,但我可以解决一下如何缩短代码的问题。您无需跟踪您的歌曲和歌曲名称,只需创建另一个dict即可用于保存包含两个或更多播放列表的所有曲目。从那里,您可以使用内置函数max()和一个简单的lambda来获取dict()中具有最高值的键:

tracks = {
u'Harry Patch (In Memory Of)': {u'playlist1': 4.0}, 
u'Fake Plastic Trees': {u'playlist2': 5.0, u'playlist1': 6.0}, 
u'The Man Who Sold The World': {u'playlist1': 3.0}, 
u'Running Up That Hill': {u'playlist1': 2.0}, 
u"Jeep's Blues": {u'playlist3': 1.0, u'playlist4':9.0}, 
u'Stella By Starlight': {u'playlist3': 1.0}, 
u'Codex': {u'playlist1': 3.0}
}

def get_top_track(tracks):
  # create a dict to hold
  # the top keys.
  ranks = {}
  for key, val in tracks.items():
    if len(val) >= 2:
      # only add the tracks
      # which have two or
      # more playlists.
      total = sum(el for el in val.values())
      ranks[key] = total
  # lastly, use the builtin in function max()
  # and a lambda to get the key with the highest value
  # in the ranks dict.
  return max(ranks, key=lambda key: ranks[key])

print(get_top_track(tracks))

哪个收益率:

>>> u'Fake Plastic Trees'

答案 2 :(得分:0)

>>> top_track = max(tracks, key=lambda k: len(tracks[k]))
>>> top_track

u'假塑料树'