re.findall which returns a dict of named capturing groups?

python, regex

Solution

Using `Pattern.finditer()` then `Match.groupdict()`:

>>> import re
>>> s = "bob sue jon richard harry"
>>> r = re.compile('(?P<name>[a-z]+)\s+(?P<name2>[a-z]+)')
>>> [m.groupdict() for m in r.finditer(s)]
[{'name2': 'sue', 'name': 'bob'}, {'name2': 'richard', 'name': 'jon'}]

Problem

Inspired by a now-deleted question; given a regex with named groups, is there a method like `findall` which returns a list of `dict` with the named capturing groups instead of a list of `tuple`? Given: ``` >>> import re >>> text = "bob sue jon richard harry" >>> pat = re.compile('(?P<name>[a-z]+)\s+(?P<name2>[a-z]+)') >>> pat.findall(text) [('bob', 'sue'), ('jon', 'richard')] ``` Should instead give: ``` [{'name': 'bob', 'name2': 'sue'}, {'name': 'jon', 'name2': 'richard'}] ```

Original source