Python: from list group by elements after a specific trigger element [duplicate]

Solution 1:

By "=>" I assume you want a dictionary if there is a preceding keyword and key be the word enclosed within the square brackets (if that's not what you intended feel free to comment and I'll edit this post)

import re

def sort(iterable):
    result = {}
    governing_match = None
    for each in list(iterable):
        match = re.findall(r"\[.{1,}\]", str(each))
        if len(match) > 0:
            governing_match = match[0][1:-1]
            result[governing_match] = []
            continue
        result[governing_match].append(each)
    return result


a=['[foo]', 'a' , 2 ,'[abcd]','bb',4,5,'kk','[efgh]',6,7,'no','[ijkl]',4,5,'lo']
for (k, v) in sort(a).items():
    print(f"{k} : {v}")

Result :

foo : ['a', 2]
abcd : ['bb', 4, 5, 'kk']
efgh : [6, 7, 'no']
ijkl : [4, 5, 'lo']

The limitation of this is that every sequence should start with an element that is enclosed within square brackets.