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 factory method..!what I am doing wrong in this!!

Do I make this code by this way!!please help me to tell the operation of ** symbol in it?

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}!"
def string_factory(listOfDictionaries):
    newList = []
    for value in listOfDictionaries:
        newList.append(template.format(value["name"],value["food"]))
    return newList    

values = [{"name": "Michelangelo", "food": "PIZZA"}, {"name": "Garfield", "food": "lasagna"}]
string_factory(values)

4 Answers

Stuart Wright
Stuart Wright
41,118 Points

** is used for dictionary unpacking. So if your dictionary is:

value = {"name": "Michelangelo", "food": "PIZZA"}

Then passing **value to a function has the same effect as passing "Michelangelo" as the "name" parameter, and "PIZZA" as the "food" parameter.

So the correct syntax for your code is simply:

    newList.append(template.format(**value))

thanks, Stuart Wright for help!! but whats wrong with my logic!

Stuart Wright
Stuart Wright
41,118 Points

The important thing here is that the template string has keyword placeholders:

template = "Hi, I'm {name} and I love to eat {food}!"

To use the format method on such a string, you need to use keyword arguments rather than positional arguments. To manually pass keyword arguments, you could have done this:

template.format(name=value["name"], food=value["food"])

But that's a little verbose, and that's why we use dictionary unpacking. Using **value passes the key value pairs as keyword arguments to the format method, which saves us having to manually do it. They are functionally equivalent though.

template.format(**value)

Note that if the template string did not have keyword placeholders, your method would have been correct:

template = "Hi, I'm {} and I love to eat {}!"
template.format(value["name"], value["food"])

yeah! I got your point, it was a great help Stuart Wright! thank you so much!