I have list of dictionaries. These dictionaries basically have just one key-value each.
For example:
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}]
I am trying to divide the list of dictionaries lst into sublists after every occurrence of a dictionary with a specific key "a". 
I tried using other ways that I saw on the internet but as I am new to python, I am not able to understand them and get the desired result. I want the final result to look like:
final_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}]],
]
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With