Capturing named groups in regex with re.findall

When I tried to answer this question: regex to separate% ages and values ​​in python , I noticed that I had to reorder the groups from the result to find everything. For instance:

data = """34% passed 23% failed 46% deferred"""
result = {key:value for value, key in re.findall('(\w+)%\s(\w+)', data)}
print(result)
>>> {'failed': '23', 'passed': '34', 'deferred': '46'}

Here's the search result:

>>> re.findall('(\w+)%\s(\w+)', data)
>>> [('34', 'passed'), ('23', 'failed'), ('46', 'deferred')]

Is there a way to change / specify the group order that re.findall returns does :

[('passed', '34'), ('failed', '23'), ('deferred', '46')]

To clarify, the question arises:

Is it possible to refine the order or reorder the groups to return the re.findall function?

I used the above example to create a dictionary to indicate a reason / usage example when you want to reorder (making the key as value and value as key)

Further clarification:

, , , re.search pr re.match. , , findall , . : - , . .

+4
3

3, OP .

, findall (, (?P<name>regex)). finditer ! . :

data = """34% passed 23% failed 46% deferred"""
for m in re.finditer('(?P<percentage>\w+)%\s(?P<word>\w+)', data):
    print( m.group('percentage'), m.group('word') )
+3

, re.findall .

, Python dict - . Python 2.x, , Python 3.x: https://docs.python.org/2/library/stdtypes.html#dict.items

collections.OrderedDict:

from collections import OrderedDict as odict

data = """34% passed 23% failed 46% deferred"""
result = odict((key,value) for value, key in re.findall('(\w+)%\s(\w+)', data))
print(result)
>>> OrderedDict([('passed', '34'), ('failed', '23'), ('deferred', '46')])

, (dict((k,v) for k,v in ...), dict ({k:v for k,v in ...}). , dict, OrderedDict ... , , .

0

Per : 2- , :

[('34', 'passed'), ('23', 'failed'), ('46', 'deferred')]

... : :

[('passed', '34'), ('failed', '23'), ('deferred', '46')]

: slicing sequence[::-1], :

a = [('34', 'passed'), ('23', 'failed'), ('46', 'deferred')]
b = [x[::-1] for x in a]
print b
0
source

All Articles