group list of dictionary I have a list of dictionaries and I want to group them by a specific value
let's say this is the list:
lst = [{'name':'john','course':'geography','grade':'80'},
       {'name':'Mary','course':'geography','grade':'70'},
       {'name':'John','course':'calculus','grade':'70'},
       {'name':'Mary','course':'calculus','grade':'70'}]

I will want all the dictionaries with the same value of &quot;name&quot; to be in a sublist, like this :
lst_new = [[{'name':'John','course':'geography','grade':'80'},
            {'name':'Mary','course':'geography','grade':'70'}],
           {'name':'John','course':'calculus','grade':'70'},
           {'name':'Mary','course':'calculus','grade':'70'}]

so I am doing it this way :
lst_new = [[elt for elt in lst if elt['name']==n] for n in np.unique(np.array([elt['name'] for elt in lst]))]

but I am feeling there are too much iterations, is there a better way to do it?
Use collections.defaultdict to &quot;bucketize&quot; the items in your list. Then collect the buckets to get the desired result.
from collections import defaultdict

bucket = defaultdict(list)

for record in lst:
    bucket[record['name']].append(record)
    
lst_new = list(bucket.values())