Crazenezz
Crazenezz

Reputation: 3456

Python Regex - Dictionary inside Dictionary

I want to create dictionary based on this data:

Input

1234STUD

Output

{'student': {'id': '1234', 'name': 'STUD'}}

Here what I do with the regex:

import re
rule = '(?P<student>((?P<id>\d{4})(?P<name>\w{4})))'
text = '1234STUD'
m = re.search(rule, text)
m.groupdict()

And for the current output (not what I wanted):

{'id': '1234', 'name': 'STUD', 'student': '1234STUD'}

Can anyone advise me what I should do to get the output that I wanted above?

Note:

This is just an example of my project, the data is more complicated than this, so if there is any way if I do with my way above (using the m.groupdict()) and it will generate what I want?

Upvotes: 0

Views: 313

Answers (2)

steveha
steveha

Reputation: 76775

You should make a function that builds the dict you want and returns it. This should use a pre-compiled regular expression pattern for speed.

import re

_pat_student_parser = re.compile(r'((?P<id>\d{4})(?P<name>\w{4}))')

def nested_dict_from_text(text):
    m = re.search(_pat_student_parser, text)
    if not m:
        raise ValueError
    d = m.groupdict()
    return { "student": d }

result = nested_dict_from_text('1234STUD')
print(result)

Upvotes: 1

Amber
Amber

Reputation: 527548

You can't create a nested dictionary with regex alone. You'll need to post-process the data to create a nested structure.

import re
rule = '(?P<id>\d{4})(?P<name>\w{4})'
text = '1234STUD'
m = re.search(rule, text)
result = {'student': m.groupdict()}

Upvotes: 2

Related Questions