Is there a function similar to re.findall but which returns dictionaries instead of tuples?

Let's say I have this line:

a= "hello world hella warld"

      

and I want to match all the regex matches:

b='(?P<hel>hell[oa])\s*(?P<wrl>w[oa]rld)'

      

I can use re.findall (b, a) and get:

[('hello', 'world'),('hella','warld')]

      

but I really want to get:

[{'hel':'hello','wrl':'world'},{'hel':'hella','wrl':'warld'}]

      

Mi queston is there any native or easy way to get this in Python?

Second question:

I wrote a function to get dictionaries:

def findalldict(regex,line):
    matches = []
    match = 1
    c = line
    while match != None and len(c)>1:
        match =re.search(regex,c)
        if match:
            matches.append(match.groupdict())
            c =c[match.end():]
    return matches

      

but I'm not sure if this is correct, are you guys seeing the error? or do you know the best way to do this?

+3


source to share


1 answer


You can use finditer

instead findall

to get an iterator MatchObject

. s:



>>> regex = re.compile('(?P<hel>hell[oa])\s*(?P<wrl>w[oa]rld)')
>>> line = "hello world hella warld"
>>> [m.groupdict() for m in regex.finditer(line)]
[{'hel': 'hello', 'wrl': 'world'}, {'hel': 'hella', 'wrl': 'warld'}]

      

+7


source







All Articles