data_garden data_garden - 6 days ago 7
Python Question

Python - Find Top item in dictionary

I want to retrieve the

top track
in the itemized data structure below:

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}
}


the logic is the following:

1 - find a track which belongs to more than one playlist.

2 - among these results, find the highest rank for this track. (adding individual playlist ranks)

I am partially there with this snippet:

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)


which prints:
11.0
, which corresponds to desired output
u'Fake Plastic Trees


but I've lost track (pardon my pun) of
track name
.

how do I retrieve track name using the code above?

ps. is there a simpler way to achieve my desired result?

Answer

While @Tim has addressed how your code works, I can address how to shorten it a bit. Instead of having to keep track of your songs and your song names, simple create another dict to use to hold all the tracks with two or more playlist. From there, you can use the builtin function max() and a simple lambda to get the key with the highest value in the 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 highes value
  # in the ranks dict.
  return max(ranks, key=lambda key: ranks[key])

print(get_top_track(tracks))

Which yields:

>>> u'Fake Plastic Trees'
Comments