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 Compiling and Loops

Pavlo Kochubei
Pavlo Kochubei
15,009 Points

.format() funciton

Hi all, When looping through matched pieces in data, we used .format() to match the string. Can somebody please explain the syntax **match.groupdict(), I've looked through documentation and can't find anything explaining this. Thanks.

for match in line.finditer(data):
        print '{first} {last} <{email}>'.format(**match.groupdict())

1 Answer

Dan Johnson
Dan Johnson
40,531 Points

The ** is being used to "unpack" the groupdict. Unpacking a dictionary means treating the key-value pairs in the dictionary as if they were keyword arguments.

For example you could assign each keyword argument a value from the dictionary one by one:

data = {"first": "Kenneth", "last": "Love", "email": "kenneth@teamtreehouse.com"}

print( "{first} {last} <{email}>".format(first=data["first"], last=data["last"], email=data["email"]) )

Or you could unpack the dictionary to supply the arguments:

data = {"first": "Kenneth", "last": "Love", "email": "kenneth@teamtreehouse.com"}

print( "{first} {last} <{email}>".format(**data) )

Both will give you the same result.

Pavlo Kochubei
Pavlo Kochubei
15,009 Points

Thanks Dan. It's much clearer now: ) But I guess I need to experiment more with 'str.format()'. Best!

Also, just in case somebody needs it, here's a link to similar examples: https://docs.python.org/2/library/string.html#format-examples