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

Devin Kulp
Devin Kulp
892 Points

Having a hard time with Dictionary Challenge...

Hello all, MY code: template = "Hi, I'm {name} and I love to eat {food}!" value = [{"name": "Chris", "food": "pizza"}, {"name": "Del", "food": "peanuts"}]

def string_factory(value): new_list = [] for value in template: new_list.append(template.format(**value)) return new_list

Some of this code was taken from others as I could not for the life of me figure out this code. I created the two dictionaries in the the value variable. I then create the string_factory function with value as the argument. I felt creating a blank list for data dump was good. And ran the for loop which likely has syntactic errors.

I've re-watched the video 3 times. Does this stuff eventually click. I am basically lost in programming and can't seem to grasp 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}!"
value = [{"name": "Chris", "food": "pizza"}, {"name": "Del", "food": "peanuts"}]

def string_factory(value):
    new_list = []
    for value in template:
        new_list.append(template.format(**value))
    return new_list

1 Answer

Umesh Ravji
Umesh Ravji
42,386 Points

Hi Devin, you won't learn anything by having an easy time. When I first started I found programming really difficult, but it's something you keep working at :)

You've decided to call your list of dictionaries value, which means inside your function you can loop over it using:

for x in value:
    # do something with x

A good idea is to name your variables something meaningful, it helps to understand what's going on and your intent can be much more clearer to someone else reading your code.

def string_factory(list_of_dictionaries):
    new_list = []
    for single_dictionary in list_of_dictionaries:
        new_list.append(template.format(**single_dictionary))
    return new_list