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

Daniel Dominique
Daniel Dominique
10,787 Points

String formatting using dictionaries

I've spent quite some time stuck on this bit of code and can't seem to figure out where I am going wrong.

Please help me understand. Thanks.

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

1 Answer

Alex Koumparos
seal-mask
.a{fill-rule:evenodd;}techdegree
Alex Koumparos
Python Development Techdegree Student 36,887 Points

Hi Daniel,

I think you're misunderstanding how dictionary packing and unpacking works. You don't need to create a dictionary variable (and you especially don't need to initialise a variable that you call 'dictionary' with an empty list). You also don't need to use a loop, you're only performing your dictionary unpacking one time.

Let's look again at what the wording of the challenge is:

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.

So the thing you are going to be unpacking is dict. But instead, your for loop is going through dict, assigning the next key from the dictionary to the variable words, then inside your loop you are trying to unpack words. Except that words isn't a dictionary, it's just a string (being the current key in the dictionary).

Even if you could unpack words, then you are just appending it to the end of a list. But that's not going to give you a string.

If you want an example of the correct syntax for dictionary unpacking, you don't even need to watch the relevant video, there's an example shown right below the video in the teacher's notes.

Hope that clears everything up

Cheers

Alex