Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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"...}


1 Answer

Kenneth Love
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!