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) 

https://repl.it/ha48/2

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) 

https://repl.it/ha48/1


Comments

Popular posts from this blog

How to understand 2 main() functions after using uftrace to profile the C++ program? -

c# - Update a combobox from a presenter (MVP) -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -