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 trialWilliam Warren
2,519 PointsNot sure how to use ** in string_factory
I'm not sure exactly how to use ** in this exercise, or if its possible to loop through kwargs at all.
# 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 {} and I love to eat {}!"
def string_factory(name=None, food=None, **kwargs):
string_list = []
for item in kwargs:
if name and food:
string_list.append(template.format(name, food))
return string_list
2 Answers
leonardbode
Courses Plus Student 4,011 PointsHello William,
Your template's placeholders need to look like this, I assume you changed them:
template = "Hi, I'm {name} and I love to eat {food}!"
The reason for this is that Python does not know which key: value to assign to which placeholder because dictionaries are unordered.
Here is my code:
template = "Hi, I'm {name} and I love to eat {food}!"
def string_factory(list_of_dicts):
return [template.format(**dictionary) for dictionary in list_of_dicts]
If you're not comfortable with list comprehension, here is a simplification of the code:
template = "Hi, I'm {name} and I love to eat {food}!"
def string_factory(list_of_dicts):
li = []
for dictionary in list_of_dicts:
li.append(template.format(**dictionary))
return li
If you have any other questions I will update my answer, if you do not have any other questions:
Remember to upvote and to choose the best answer so that your question receives a checkmark in forums.
Kind regards,
Leo
William Warren
2,519 PointsThanks Leonard Bode.
Brandon Bell
1,107 PointsBrandon Bell
1,107 PointsLeonard Bode - The instructions literally tell you to use it.
"Write a function named string_factory that accepts a list of dictionaries as an argument. Return a new list of strings made by using ** for each dictionary in the list and the template string provided."
leonardbode
Courses Plus Student 4,011 Pointsleonardbode
Courses Plus Student 4,011 PointsBrandon Bell I edited my answer.