Home > Enterprise >  Group dictionaries in list of dictionaries based on consecutive integers as key values
Group dictionaries in list of dictionaries based on consecutive integers as key values

Time:06-14

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!

CodePudding user response:

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'])]
  • Related