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

I cannot understand how to complete this challenge and how to unpack python dictionaries

I feel as if this code challenge is drastically different from the video prior to it and I cannot seem to figure out how to do this. It also doesn't help that I cannot quite understand what packing and unpacking a dictionary means and how you would apply it to this challenge?

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

2 Answers

Dave StSomeWhere
Dave StSomeWhere
19,870 Points

Here's how I think about this challenge...

First you are receiving a dictionary which looks like:

dict1 = {
    "name": "Dima",
    "food": "Pizza"
}

So then you can access the dictionary with:

my_name = dict1["name"]
my_food = dict1["food"]

Now if you pass dict1 to a function, unpacking will break out the function into the key value pairs

If I call some_function(dict1) - passing the dictionary

Then I can use the slick unpacking to break out the key value pairs...

def some_function(**dict_in):
    #  do stuff with name and food

#  is a spiffy way to do below, where you don't need to know the specific dictionary details
#  for this example it is the same as 
def some_function(name="Dima", food="Pizza"):
    # do stuff with name and food

Hope that helps

Thanks for the response. I understand it a bit better now.

unknown member
PLUS
unknown member
Courses Plus Student 18,949 Points

Insert **dict into format method, press Check Work and boom - you're done. The thing is when you put dictionary through this function it will look for keys "name" and "food" and at the end will return values respectively.