How to group a list of Dictionaries into a sublists of Dictionaries by one of their key-values? [closed]

StackOverflow https://stackoverflow.com/questions/23598318

  •  20-07-2023
  •  | 
  •  

Question

How to group a list of Dictionaries into a sublists of Dictionaries by one of their key-values?

For example, I'd like to change this list of Dictionaries into sublists of Dictionaries

lst = [{'A':12,'B':32,'ID':333},{'Z':32,'C':43,'ID':111},{'D':43,'J':31,'ID':222},{'a':32,'b':31,'ID':222},{'D':43,'ID':333},{'a':89,'d':31,'ID':222},{'C':83,'ID':111}]


Desired_lst = [[{'A':12,'B':32,'ID':333},{'D':43,'ID':333}],[{'Z':32,'C':43,'ID':111},{'C':83,'ID':111}],[{'D':43,'J':31,'ID':222},{'a':32,'b':31,'ID':222},{'a':89,'d':31,'ID':222}]]

I've tried the following, which doesn't work, because I'm not sure how to apply groupby or sorted to a Dictionary.

from itertools import groupby
from operator import itemgetter


Desired_List = [list(grp) for key, grp in itertools.groupby(sorted(lst, key=operator.itemgetter(['ID'])),key=operator.itemgetter(['ID'))]
Was it helpful?

Solution

I think the issue with your current code is how you're calling itemgetter. The arguments should be the keys to use to access the object, without any container. You're passing a list, which isn't a legal dictionary key. Try:

keyfunc = operator.itemgetter("ID")
Desired_List = [list(grp) for key, grp in itertools.groupby(sorted(lst, key=keyfunc),
                                                            key=keyfunc)]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top