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

Nikhil Alexander
Nikhil Alexander
1,444 Points

this is the dictionary code challenge... i dint get what to do

help me out

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

favorite_food({"name":"Tony", "food":"shawarma"})

1 Answer

andren
andren
28,558 Points

This challenge is trying to teach you how dictionary unpacking (**) works. When you unpack a dictionary you get back a pair of key-value pairs corresponding to the keys and values in the dictionary. So a dictionary like this: {"name":"Tony", "food":"shawarma"} would result in this when unpacked: name = "Tony", food = "shawarma".

Now if you look at the unpacked dictionary and then at the code you have written you might notice a certain similarity. The unpacked dictionary produces the exact same values that you have manually typed into the format method. Because of that you can actually just replace that text with the unpacked dictionary.

Like this:

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

favorite_food({"name":"Tony", "food":"shawarma"})

Now whatever the value of name and food is in the dictionary will populate the name and food placeholders in the string you return.