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

Need help for this question.

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.

string_factory.py
# Example:

# 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 unpacker(name, food):
    return template.format(name,food)

new_list = []

def string_factory(a_list_of_dictionary):
    for each_dic in a_list_of_dictionary:
        huahua = unpacker(**each_dic)
        new_list.append(huahua)
    return new_list
string_factory(values)

2 Answers

Hi there,

I approached this one by looping over the original list of dictionaries, pulling out each one in turn. I then created a variable to hold each name/food pair and appended those onto a blank list I created before the loop. I used the template for this and expressly assigned something to name and food. Once the loop was complete, I returned the new list.

This works but doesn't use the ** approach. I'm sure it could be easily amended, though.

I hope it helps.

Steve.

def string_factory(list_dict):

    new_list = []
    # loop list of dictionaries
    for one_dict in list_dict:  
        aname = one_dict["name"]
        afood = one_dict["food"]
        new_list.append(template.format(name=aname, food=afood))
    return new_list
Moosa Bonomali
Moosa Bonomali
6,297 Points

Adding to Steve's answer, you can use unpacking in this way;

    def string_factory(list_dict):

        new_list = []
        # loop list of dictionaries
        for one_dict in list_dict:  
            new_list.append(template.format(**one_dict))
        return new_list

[MOD: edited code block - srh]

Much cleaner solution! Thank you. [EDIT - code amended] :smile:

Steve.