Let's use re.findall
here:
>>> import re
>>> dict(re.findall(r'(?=\S|^)(.+?): (\S+)', text))
{'Date': '07/14/1995', 'Subject text': 'Something-cool', 'Time': '11:31:50'}
Or, if you insist on the format,
>>> {k : [v] for k, v in re.findall(r'(?=\S|^)(.+?): (\S+)', text)}
{
'Date' : ['07/14/1995'],
'Subject text': ['Something-cool'],
'Time' : ['11:31:50']
}
Details
(?= # lookahead
\S # anything that isn't a space
| # OR
^ # start of line
)
(.+?) # 1st capture group - 1 or more characters, until...
: # ...a colon
\s # space
(\S+) # 2nd capture group - one or more characters that are not wsp
Semantically, this regex means "get me all pairs of items that follow this particular pattern of something followed by a colon and whitespace and a bunch of characters that are not whitespace". The lookahead at the start is so that the groups are not captured with a leading whitespace (and lookbehinds support only fixed-width assertions, so).
Note: This will fail if your values have spaces in them.
If you're doing this for multiple lines in a text file, let's build on this regex and use a defaultdict
:
from collections import defaultdict
d = defaultdict(list)
with open(file) as f:
for text in file:
for k, v in re.findall(r'(?=\S|^)(.+?): (\S+)', text.rstrip()):
d[k].append(v)
This will add one or more values to your dictionary for a given key.