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

William Warren
William Warren
2,519 Points

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

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 {} 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

Hello 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

Leonard 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."

Brandon Bell I edited my answer.