KT.Thompson
KT.Thompson

Reputation: 149

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

I have a list looks like the following:

content1,2,3... is the message, which can be anything

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'
}

Upvotes: 1

Views: 22

Answers (1)

mozway
mozway

Reputation: 260780

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'}

Upvotes: 2

Related Questions