-1

I have a list with dictionaries that I would like to split or group into new dictionary lists based on a key with consecutive integers. This is my input:

lst=[{'name':'sam','class':1},
     {'name':'adam','class':2},
     {'name':'smith','class':3},
     {'name':'john','class':10},
     {'name':'r.','class':11},
     {'name':'doe','class':12}
     ]

Expected output:

[[{'name':'sam','class':1},
 {'name':'adam','class':2},
 {'name':'smith','class':3}],
 [{'name':'john','class':10},
 {'name':'r.','class':11},
 {'name':'doe','class':12}]
 ]

I'm aware I can sort a list like this, but I don't know how to do the same with a list of dictionaries. In the end, I would like to group the names together. As you can tell from the example, I have a list of dictionaries with person's names as strings and am grouping them so that first, middle and last names are in unique list. I get these person dictionaries based on a NER machine learning algorithm that I run over a string containing names, but also other information.

Thank you!

steca
  • 77
  • 5
  • 1
    iterate over the list, if the current class is consecutive to the previous one, append the dictionary to the current list, otherwise start a new list with that dictionary –  Jun 13 '22 at 10:33
  • Does sorting a list of dictionaries solve your problem? If so you can try this SO: https://stackoverflow.com/questions/72899/ – Daquisu Jun 13 '22 at 10:35

1 Answers1

1

You can use the following (as long as your lst is in class value order):

from itertools import groupby

grouped = [[v for k, v in g] for k, g in groupby(enumerate(lst), lambda v: v[0] - v[1]['class'])]
Jon Clements
  • 138,671
  • 33
  • 247
  • 280