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

Help with Unpacking

Hi! I'm very confused about this whole unpacking situation. Could someone help?

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

favorite_food(**{"name ": "Megan", "food": "Tacos"})

Alright Megs:

Inside of the function we need create two variables: "name" and "food"

Now, the "name" and "food" variables need to receive the VALUES of the KEYS that are inside the dictionary being passed to the function favorite_food... I know you know how to do that.

name = dict['name']

I bet you now now how to create the second variable "food"

Second step is to return the string with our two new created variables inside the format(name, food) function.

1 Answer

Viraj Deshaval
Viraj Deshaval
4,874 Points

To solve this challenge you only need to unpack Dictionary as below.

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

What this does is, we pass the keyword argument while calling the function and then we grab this key word arguments into dict variable and unpack it. When you pass **dict you are actually now unpacking the key word arguments. I hope this helps. Let me know if you still require more explanation.

It works! Thanks! I was just confused about where to put the "**"