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

Hi, how do string format placeholders "name" and "food" between the {} have an effect on answering this challenge?

template = "Hi, I'm {name} and I love to eat {food}!"

After removing these from the string assigned to the variable "template", the tests no longer passed. Any help would be greatly appreciated especially a documented Python source. Thanks in advance.

string_factory.py
# Example:
# values = [{"name": "Michelangelo", "food": "PIZZA"}, {"name": "Garfield", "food": "lasagna"}]
# string_factory(values)
# ["Hi, I'm Michelangelo and I love to eat PIZZA!", "Hi, I'm Garfield and I love to eat lasagna!"]

template = "Hi, I'm {name} and I love to eat {food}!"

1 Answer

Stuart Wright
Stuart Wright
41,120 Points

Those are keyword placeholders, and remember you're passing a dictionary to be unpacked as the arguments of this function. Dictionaries have keys ('name' and 'food' in this case). Without the named placeholders, there's no way for the program to know which dictionary value goes where.

Not an official source, but here's a related conversation on StackOverflow which will hopefully help to get your head around this idea:

https://stackoverflow.com/questions/5952344/how-do-i-format-a-string-using-a-dictionary-in-python-3-x

Thank you Stuart for the prompt reply! This is what I was looking for to assist with the understanding.