python - Work with list and dictionary -
i have list:
list = [ {'album': '1', 'artist': 'pedro', 'title': 'duhast'}, {'album': '2', 'artist': 'hose', 'title':'star boy'}, {'album': '1', 'artist': 'migel', 'title': 'lemon tree'} ] i need group/sort list :
list = [ {'album': '1', 'tracks': [ {'artist': 'pedro', 'title': 'duhast'}, {'artist': 'migel', 'title': 'lemon tree'}] }, {'album': '2', 'tracks':[ {'artist': 'hose', 'title':'star boy'}] } ] more precisely, need group tracks albums. ideas make easy?
1-liner :)
from itertools import groupby list = [{'album': '1', 'artist': 'pedro', 'title': 'duhast'}, {'album': '2', 'artist': 'hose', 'title':'star boy'}, {'album': '1', 'artist': 'migel', 'title': 'lemon tree'}] res = [{'album': album, 'tracks': [{'artist': track['artist'], 'title': track['title']} track in tracks]} album, tracks in groupby(sorted(list, key=lambda x: x['album']), lambda x: x['album'])] print(res) as @prune mentioned, groupby function can used group list specified key function. in order work, list must sorted key.
personally, find above solution little hard read... gives same result:
from itertools import groupby list = [{'album': '1', 'artist': 'pedro', 'title': 'duhast'}, {'album': '2', 'artist': 'hose', 'title':'star boy'}, {'album': '1', 'artist': 'migel', 'title': 'lemon tree'}] res = [] album, tracks in groupby(sorted(list, key=lambda x: x['album']), lambda x: x['album']): res.append({'album': album, 'tracks': [{'artist': track['artist'], 'title': track['title']} track in tracks]}) print(res)
Comments
Post a Comment