Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Group list by some rows in Python

I have same list of lists

l = [
  ['one'],
  ['', 'any'],
  ['', 'anynay'],
  ['', 'val'],
  ['two'],
  ['', 'dss'],
  ['tr'],
  ['', 'ff'],
  ['', 'mnb']
]

I want get dict group by rows if row[0] not empty

d = {
  'one': [['', 'any'], ['', 'anynay'], ['', 'val']],
  'two': [['', 'dss']],
  'tr': [['', 'ff'], ['', 'mb']]
}

All my attempts is wrong fundamentally

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can simply iterate over the items and add things as they come along. This does however imply that l is strictly in the format described.

d = {}
current = None
for row in l:
    if row[0]:
        # New section starts
        assert len(row) == 1
        assert row[0] not in d
        # Create new list for that key
        d[row[0]] = current = []
    else:
        # Add item to the current list
        current.append(row)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading