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

how to get the strings and concat several strings to one string between two index?

I have a list looks like the following:

lst1 = [
'2022-02-21 14:26:02 user1',
'content1',
'content2',
'content3',
'2022-02-24 14:40:12 user2',
'content11',
'content22',
'2022-02-25 14:26:02 user1',
'content12',
'2022-02-24 14:40:12 user2',
'content13'
]

I want to convert it to a dictionary which contains something like '2022-02-21 14:26:02 user1' as the key and its content as corresponding values.

{
'2022-02-21 14:26:02 user1':'content1;content2;content3',
'2022-02-24 14:40:12 user2':'content11;content22',
'2022-02-25 14:26:02 user1':'content12',
'2022-02-24 14:40:12 user2':'content13'
}

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 don’t need pandas here, a simple python loop would work:

d = {}
key = None
for x in lst1:
    if x[:4].isdigit():
        key = x
        continue
    if key in d:
        d[key] = d[key]+f';{x}'
    else:
        d[key] = x

output:

{'2022-02-21 14:26:02 user1': 'content1;content2;content3',
 '2022-02-24 14:40:12 user2': 'content11;content22;content13',
 '2022-02-25 14:26:02 user1': 'content12'}
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