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! While you're at it, check out some resources Treehouse students have shared here.

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 Python Collections (2016, retired 2019) Dictionaries String Formatting with Dictionaries

the usage of double asterisks

I am super confused between the packing and unpacking video examples and the unpacking challenge.

In the def packer example, we use the double asterisk so any key words and values that we add at the end will automatically pack into a dictionary.

For the unpacking challenge, why cant we use the double asterisk in the beginning like def favorite(dict)? Why does the code only work when we include the double asterisk in the format .format(dict)?

Regards, Gia

string_factory.py
def favorite_food(dict):
    return "Hi, I'm {name} and I love to eat {food}!".format(**dict)

favorite_food({"name": "hoang", "food": "sushi"})

1 Answer

Steven Parker
Steven Parker
231,269 Points

To make sure your inline code is readable, use Markdown formatting when you post.
:point_right: Like this, so * and ** can be seen.

But the "splat" operator does different things depending on where you use it. When used in a function call, such as "format" in this example, it becomes an unpacking operator. It takes a dictionary and converts it into individual keyword arguments.

But when used in a function definition, it becomes a packing operator. Then it converts separate keyword arguments into a dictionary.

So the choice of where to use it is determined by what you are starting with (a dictionary in this case) and what you need (arguments for "format").

Thanks