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 trialnicholasgrzywinski
12,830 PointsString Formatting with Dictionaries Challenge
I feel like I should be passing this challenge, when I run this code on my computer it works just fine, the strings variable produces a list of strings formatted by the dicts in values. But every time I press the check work button I get this error: Bummer! string_factory() missing 1 required positional argument: 'template'
# 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}!"
values = [{"name": "Michelangelo", "food": "PIZZA"}, {"name": "Garlield", "food": "Lasagna"}]
def string_factory(values, template):
strings = []
for value in values:
strings.append(template.format(**value))
return strings
3 Answers
gyorgyandorka
13,811 PointsHi Nicholas! I've figured out the problem: you shoudn't give an additional parameter to the function and pass in the template string as an argument - just reach for that pre-defined global variable instead. (Yeah, our function loses its portability if we make it dependent on variables outside its scope, so I totally understand that you automatically declared another parameter - but that's how this challenge works anyway...)
Matthew Kelty
2,575 PointsI used:
def string_factory(values):
return [template.format(**x) for x in values]
gyorgyandorka
13,811 PointsList comprehension, clever :) (By the way, x
could be renamed to value
, just as in Nicholas' code, thus following the common pattern of foo
-foos
when naming an iterable and its items)
If the above construct is not familiar for someone, here is Kenny's workshop on comprehensions:
https://teamtreehouse.com/library/python-comprehensions-2
Lukáš Miketa
4,714 PointsWhy doesn't template have to be in the paranthesis like this def string_factory(values, template)?
gyorgyandorka
13,811 PointsIt could be (and in fact, should), but this challenge - for whatever reason - requires that you use only one parameter, and refer to that pre-defined template
variable outside the function.
nicholasgrzywinski
12,830 Pointsnicholasgrzywinski
12,830 PointsThanks.