python - Grouping list by unique values -
i have list
list = [{'album': 'spring times', 'artist': 'momo pulse'}, {'album': 'spring times', 'artist': 'k.oshkin'}, {'album': 'damn ', 'artist': 'florent b'}]
i want group get:
list = [{'album': 'spring times', 'artist1': 'momo pulse', 'artist2': 'k.oshkin'}, {'album': 'damn ', 'artist1': 'florent b'}]
how can that? ideas?
from itertools import groupby # input my_list = [{'album': 'spring times', 'artist': 'momo pulse'}, {'album': 'spring times', 'artist': 'k.oshkin'}, {'album': 'damn ', 'artist': 'florent b'}] # have function return merged dictionary after update def merge_dict(a, b): a.update(b) return # key function sort , groupby sortkey = lambda d: d['album'] # sort , group album my_groups = groupby(sorted(my_list, key=sortkey), key=sortkey) # generate output print [merge_dict({'album':k},{'artist'+str(i+1):d['artist'] i, d in enumerate(g)}) k, g in my_groups]
Comments
Post a Comment