简体   繁体   中英

Grouping list by unique values

I have a list

list = [{'album': 'Spring Times', 'artist': 'Momo Pulse'}, {'album': 'Spring Times', 'artist': 'K.oshkin'}, {'album': 'Damn ', 'artist': 'Florent B'}]

I want to group it to get:

list = [{'album': 'Spring Times', 'artist1': 'Momo Pulse', 'artist2': 'K.oshkin'}, {'album': 'Damn ', 'artist1': 'Florent B'}]

How can I do that? Any 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 a function to return the merged dictionary after an update
def merge_dict(a, b):
    a.update(b)
    return a

# key function for sort and groupby
sortkey = lambda d: d['album']

# Sort and group by album
my_groups = groupby(sorted(my_list, key=sortkey), key=sortkey)

# Generate output
print [merge_dict({'album':k},{'artist'+str(i+1):d['artist'] for i, d in enumerate(g)}) for k, g in my_groups]  
from collections import defaultdict

l = [{'album': 'Spring Times', 'artist': 'Momo Pulse'}, 
     {'album': 'Spring Times', 'artist': 'K.oshkin'}, 
     {'album': 'Damn ', 'artist': 'Florent B'}]
d = defaultdict(list)

for record in l:
    d[record['album']].append(record['artist'])

We now have a dictionary mapping album names to a list of artists.

final = []

for album, artists in d.items():
    temp = {'album': album}
    for i, x in enumerate(artists, start=1):
        temp['artist{}'.format(i)] = x
    final.append(temp)

print(final)

prints

[{'album': 'Damn ', 'artist1': 'Florent B'}, {'album': 'Spring Times', 'artist1': 'Momo Pulse', 'artist2': 'K.oshkin'}]
l = [{'album': 'Spring Times', 'artist': 'Momo Pulse'}, {'album': 'Spring Times', 'artist': 'K.oshkin'}, {'album': 'Damn ', 'artist': 'Florent B'}]

albums = {}
for el in l:
    album = albums.setdefault(el['album'], {})
    artist_id = sum(1 for k in album if k.startswith('artist'))
    album['artist'+str(artist_id)] = el['artist']

l2 = albums.values() #This is your output

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM