Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

regex

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'}] 
like image 769
beerbajay Avatar asked Jun 19 '12 15:06

beerbajay


People also ask

What does re Findall return?

The re. findall() method returns a list of strings. Each string element is a matching substring of the string argument.

What type of thing does Findall return?

If the pattern has one capturing group, the findall() function returns a list of strings that match the group. If the pattern has multiple capturing groups, the findall() function returns the tuples of strings that match the groups.


1 Answers

>>> 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'}] 
like image 135
Nolen Royalty Avatar answered Sep 19 '22 17:09

Nolen Royalty