Python Practice › RegEx Programs › Program 13
Parse log lines with named groups
Write a Python program to parse “LEVEL date message” log lines into dictionaries.
Output
{'level': 'ERROR', 'date': '2026-11-02', 'msg': 'db timeout'}
{'level': 'INFO', 'date': '2026-11-02', 'msg': 'started'}Approach
- Named groups and
groupdict().
Solution
import re LINE = re.compile(r"(?P<level>[A-Z]+) (?P<date>\d{4}-\d{2}-\d{2}) (?P<msg>.+)")for line in ["ERROR 2026-11-02 db timeout", "INFO 2026-11-02 started"]: print(LINE.match(line).groupdict())Output
{'level': 'ERROR', 'date': '2026-11-02', 'msg': 'db timeout'}
{'level': 'INFO', 'date': '2026-11-02', 'msg': 'started'}Learn the concept
New to this topic? Read the lesson, then come back.