Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting list of dictionary into sublists after the occurence of particular key of dictionary

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}]],
]
like image 343
vishal babu Avatar asked Sep 15 '17 10:09

vishal babu


2 Answers

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}]]
like image 68
Martijn Pieters Avatar answered Nov 20 '22 16:11

Martijn Pieters


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)
like image 3
Danil Speransky Avatar answered Nov 20 '22 16:11

Danil Speransky