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

Please help! String formatting with dictionaries

Hi, this code runs perfect in my computer but in treehouse I keep getting Bummer! dont understand why!!!

string_factory.py
dicts = [{"name": "Michelangelo", "food": "PIZZA"}, {"name": "Garfield", "food": "lasagna"}]
template = "Hi, I'm {name} and I love to eat {food}!"

def string_factory(dicts, template): 
    new_list = []
    for names_and_food in dicts:
        new_template = template.format(**names_and_food)
        new_list.append(new_template)
    print (new_list)

string_factory (dicts, template)

3 Answers

OK, a few issues here.

First, they want you to return the list, not print it.

Second, don't put templates as an argument into the function. It can just grab the value from the templates variable, which will work fine.

Third, you don't need to call the function, just define it.

Finally, in the format part of the function, the placeholder name must be given a value to fill in. Set name equal to the dict item name and set food equal to the dict item food.

Here is the code for the function prewritten so you don't have to do all this yourself.

def string_factory(dicts): 
    new_list = []
    for name_and_food in dicts:
        new_template = template.format(name=name_and_food["name"], food=name_and_food["food"])
        new_list.append(new_template)
    return new_list

The dictionary and template definitions, you can keep in there.

many thanks Zack!! that makes a lot of sense!

You are welcome.

:x: Actually Python doesn't care about spaces between function names and parameters (as long as the arguments are wrapped in parentheses).

James J. McCombie
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
James J. McCombie
Python Web Development Techdegree Graduate 21,199 Points

Thanks for the comment Alexander, but given this was a treehouse challenge, I felt it might be something that would stop the task passing, keep up the good work