data_garden data_garden - 1 month ago 8
Python Question

Python - simplifying code with list comprehension

given the playlists:

energy_playlist = [{u'track': u'Nude', u'feature': u'energy', u'value': 0.342, u'artist': u'Radiohead'}, {u'track': u'Kaleidoscope', u'feature': u'energy', u'value': 0.285, u'artist': u'Coldplay'}, {u'track': u'Faust Arp', u'feature': u'energy', u'value': 0.289, u'artist': u'Radiohead'}, {u'track': u'Running Up That Hill', u'feature': u'energy', u'value': 0.356, u'artist': u'Placebo'}, {u'track': u'Codex', u'feature': u'energy', u'value': 0.128, u'artist': u'Radiohead'}, {u'track': u'True Love Waits', u'feature': u'energy', u'value': 0.132, u'artist': u'Radiohead'}, {u'track': u'Asleep - 2011 Remastered Version', u'feature': u'energy', u'value': 0.255, u'artist': u'The Smiths'}, {u'track': u'Glass Eyes', u'feature': u'energy', u'value': 0.11, u'artist': u'Radiohead'}, {u'track': u'Pyramid Song', u'feature': u'energy', u'value': 0.335, u'artist': u'Radiohead'}, {u'track': u'Life On Mars? - 2015 Remastered Version', u'feature': u'energy', u'value': 0.384, u'artist': u'David Bowie'}, {u'track': u'Exit Music (For a Film)', u'feature': u'energy', u'value': 0.276, u'artist': u'Radiohead'}, {u'track': u'Videotape', u'feature': u'energy', u'value': 0.384, u'artist': u'Radiohead'}, {u'track': u'High And Dry', u'feature': u'energy', u'value': 0.383, u'artist': u'Radiohead'}]


and

tempo_playlist = [{u'track': u'Codex', u'feature': u'tempo', u'value': 58.993, u'artist': u'Radiohead'}, {u'track': u'Pyramid Song', u'feature': u'tempo', u'value': 77.078, u'artist': u'Radiohead'}, {u'track': u'Videotape', u'feature': u'tempo', u'value': 77.412, u'artist': u'Radiohead'}]


I can find the matching
tracks
in this way:

for d1 in energy_playlist:
for d2 in tempo_playlist:
if d1['track'] == d2['track']:
print (d2['track'])


how do I manage to do the same with a
list comprehension
in one line, assigned to a
variable
final_playlist
?

Answer

convert your whole code into list comprehension

final_playlist = [d2['track'] for d1 in energy_playlist for d2 in tempo_playlist if d1['track'] == d2['track']]
Comments