Splitting list of dictionary into sublists after the occurence of particular key of dictionary
You can use a generator that collects elements and yields when the condition is met:
def split_by_key(lst, key):
collected = []
for d in lst:
collected.append(d)
if key in d:
yield collected
collected = []
if collected: # yield any remainder
yield collected
final_lst = list(split_by_key(lst, 'a'))
Demo:
>>> lst = [{'x': 23}, {'y': 23432}, {'z': 78451}, {'a': 564}, {'x': 45},
... {'y': 7546}, {'a': 4564}, {'x': 54568}, {'y': 4515}, {'z': 78457},
... {'b': 5467}, {'a': 784}]
>>> list(split_by_key(lst, 'a'))
[[{'x': 23}, {'y': 23432}, {'z': 78451}, {'a': 564}], [{'x': 45}, {'y': 7546}, {'a': 4564}], [{'x': 54568}, {'y': 4515}, {'z': 78457}, {'b': 5467}, {'a': 784}]]
>>> pprint(_)
[[{'x': 23}, {'y': 23432}, {'z': 78451}, {'a': 564}],
[{'x': 45}, {'y': 7546}, {'a': 4564}],
[{'x': 54568}, {'y': 4515}, {'z': 78457}, {'b': 5467}, {'a': 784}]]
Here is a straightforward solution:
result = []
for item in lst:
if not result or 'a' in result[-1][-1]:
result.append([])
result[-1].append(item)