Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Regular Expressions in Python Introduction to Regular Expressions Groups

Tobias Edwards
Tobias Edwards
14,458 Points

Regular Expressions: re.match() or re.search() to return multiple dictionaries

In the Python course: Introduction to Regular Expressions in the Groups video, Kenneth teaches how to use re.search() to loop through a string made up of contacts names, jobs, emails...etc... and return a dictionary of that contacts information.

My question is: How would I use re.search() or re.match() to print multiple dictionaries, each one of a different contact?

In the Groups video, Kenneth Love prints a dictionary containing information for himself, but how could I print all the dictionaries for all the contacts?

Instead of printing:

{"first_name" : "Kenneth", "second_name" : "Love"} # and other info

How could I print:

{"first_name" : "Kenneth", "second_name" : "Love"...}

{"first_name" : "Jim", "second_name" : "Turner"....}

{"first_name" : "Sherlock", "second_name" : "Holmes"...}

etc...

1 Answer

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

In the last video of the course, we use a method named re.finditer(). This method gives us an iterator (you can think of it as a list, but you can't index or slice it) that we can loop though. Each item in that iterator is a Match object, like we get with re.match() or re.search(), so you can do match.groupdict() for that object, assuming you called it match in your for loop.

Amazing, thank you so much for the explanation of it!