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 trialRachael A
1,044 PointsI can't solve this annoying problem
I have tried many ways to solve this but I keep getting the same errors like Bummer! 'name'.
# 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!"]
values = [{"name": "Michelangelo", "food": "PIZZA"}, {"name": "Garfield", "food": "lasagna"}]
template = "Hi, I'm {name} and I love to eat {food}!"
def string_factory(values):
values_list = []
for name, food in values:
values_list.append(template.format(name, food))
return(values_list)
I have also tried this and get Bummer! list indices must be integers or slices, not str
values = [{"name": "Michelangelo", "food": "PIZZA"}, {"name": "Garfield", "food": "lasagna"}]
template = "Hi, I'm {name} and I love to eat {food}!"
def string_factory(values):
values_list = []
for name, food in values:
name = values["name"]
food = values["food"]
values_list.append(template.format(name, food))
return(values_list)
3 Answers
Tonye Jack
Full Stack JavaScript Techdegree Student 12,469 PointsYour thinking about it too much just loop through each item and unpack the values.
# One liner
string_factory = lambda v: list(map(lambda kw: template.format(**kw), v))
# Long example
def string_factory(values):
return_list = []
for value in values:
return_list.append(template.format(**value))
return return_list
Tonye Jack
Full Stack JavaScript Techdegree Student 12,469 PointsIm more of a teacher than student
Josh Bennett
15,258 Pointsnope, got an error,
couldn't import `string_factory`.
Tonye Jack
Full Stack JavaScript Techdegree Student 12,469 PointsAre you importing string_factory
string_factory = lambda v: list(map(lambda kw: template.format(**kw), v))
string_factory(values)
# Outputs :
# ["Hi, I'm Michelangelo and I love to eat PIZZA!", "Hi, I'm Garfield and I love to eat lasagna!"]
Rachael A
1,044 PointsRachael A
1,044 PointsThank you so much!!! this was driving me crazy. I didn't quite understand how the unpacking thing worked. I was just wondering with the one-liner approach have we covered lambda or maps yet? or did you know this from other tutorials?