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

Elgene Ee
Elgene Ee
3,554 Points

Unpack string_factory

Hi guys, really need your help on this one... Kinda stuck

string_factory.py
#accepts dictionary as argument
#unpack that dictionary and pass it to the format method as keyword
#return the resulting string
def favorite_food(dict):
    return "Hi, I'm {name} and I love to eat {food}!".format()

1 Answer

Mathew Tran
PLUS
Mathew Tran
Courses Plus Student 10,205 Points

In the format function, pass in dict with the following syntax: **dict.

What this does is unpack the dictionary into the format function call. Allowing access to keys that are provided in the dict parameter while it is being called

It's essentially doing this for you

  "Hi, I'm" + dict["name"] + "and I love to eat" + dict["food"] + "!"

Hope this makes sense!

Matt

Chris Freeman
Chris Freeman
Treehouse Moderator 68,423 Points

If the passing in dict was {"name": "Kenneth", "food": "pizza"} then using **dict as an argument to .format() would be the same as .format(name="Kenneth", food="pizza")