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

A quiz question!

Let's test unpacking dictionaries in keyword arguments. You've used the string .format() method before to fill in blank placeholders. If you give the placeholder a name, though, like in template below, you fill it in through keyword arguments to .format(), like this: template.format(name="Kenneth", food="tacos") 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. I'm pretty confused right now. Could you help me by being a little precise?

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

1 Answer

Hi there!

Don't worry it's not just you - this is one of the most frequently asked questions on the python track lol. From what I can figure it's so confusingly worded because there's a few different ways you could do this, and they wan't to remind you to use dictionary unpacking as seen in the previous video, not any other method you may know already (knowledge comes from going down the path less travelled after all!). The problem seems to be that in being overly detailed in the wording, the actual question seems to get lost.

To paraphrase it, what the question is actually asking is:

  • Make a function called string_format
  • This function will take one argument - a list of dictionaries
  • The function will go through each dictionary in the list and insert it's values into the template string
  • The function will return a list of template strings with the values inserted.
  • Use dictionary unpacking for this.

Example inputs and outputs:

input_list = [
    {"name": "Michelangelo", "food": "PIZZA"}, 
    {"name": "Garfield", "food": "lasagna"}
]

output_list = [
    "Hi, I'm Michelangelo and I love to eat PIZZA!"
    "Hi, I'm Garfield and I love to eat lasagna!"
]

Hope it helps :)