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

String 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'

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}!"
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

Hi 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...)

Thanks.

Matthew Kelty
Matthew Kelty
2,575 Points

I used:

def string_factory(values):
    return [template.format(**x) for x in values]

List 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
Lukáš Miketa
4,714 Points

Why doesn't template have to be in the paranthesis like this def string_factory(values, template)?

It 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.