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

Kento Nambara
Kento Nambara
1,764 Points

String Formatting With Dictionaries Challenge

I was able to complete this challenge, but I would much appreciate any feedback on how to make it simpler/better. Since I didn't use ** as was written on the instruction, I feel like I did not code the best way I could have. Thank you!

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(list_of_dict):
    new_string = []
    for dicts in list_of_dict:
        if dicts["name"] and dicts["food"]:
            new_string.append(template.format(name=dicts["name"], food=dicts["food"]))
        else:
            pass
    return(new_string)

1 Answer

andren
andren
28,558 Points

Your code is pretty good, there are only two things I would have done differently:

  1. While not a bad practice in the real world, since the challenge specifies that all of the dictionaries will contain a name and food key it's not really necessary to check for those in your code before you use them.

  2. When you unpack a dictionary you end up with a key-value pair that reflect the contents of the dictionary. So if you had a dictionary that contained {"name": "AndrΓ©", "food": "Pizza"} for example then unpacking that dictionary would produce: name="AndrΓ©", food="Pizza". As you might be able to tell those key-value pairs are exactly what you end up using in the call to the format method. Which means that you can actually just unpack the dictionary in the call to the format method and not type out any of that yourself.

Here is how I would have written this method:

def string_factory(list_of_dict):
    new_string = []
    for dicts in list_of_dict:
        new_string.append(template.format(**dicts))
    return(new_string)
Kento Nambara
Kento Nambara
1,764 Points

Thank you for your detailed answer!