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

Natalia Henderson
Natalia Henderson
5,190 Points

How to unpack the dictionary

You've used the string .format() method before to fill in blank placeholders. If you use a placeholder of {food} in the string, then you pass a keyword argument of food to .format(). The {food} placeholder in the string will be replaced with the value of the food keyword argument.

"Hi, I'm {name} and I love to eat {food}!".format(name="Kenneth", food="tacos")

Returns "Hi, I'm Kenneth and I love to eat tacos!"

Complete the favorite_food function below. It accepts a dictionary as an argument. Your function should unpack that dictionary and pass it to the format method as keywords, then return the resulting string.

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

1 Answer

Remember, when you are formatting a string, you just need {}, they just added the words there for your reference.