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

Mattias Nelson
Mattias Nelson
961 Points

Inquiry - Can this be shortened/trimmed? (Challenge: String Formatting With Dictionaries)

Even though I was able to meet the demands of the challenge, I can't help but feel as though there's a way to shorten out the glob of code I created.

In addition, I also have a couple of questions which may in turn answer/solve my original inquiry.

  • When passing a list of dictionaries, can you directly access each individual dictionary OR do you need to "unpack" each individual dictionary within the list?

  • Can dictionaries contain functions?

  • Based on what you've seen with my code, what do you believe needs to be worked upon?

Thank you for your time reader, and I'm looking forward to your replies/insight.

def string_factory(listage):

    # Create an empty list to acquire/append each string
    master_list = []

    # Takes in the values of each dictionary from 'listage'
    # and returns them in the properly formatted string
    # as the challenge demands
    def extractor(name = None, food = None):

        return "Hi, I'm {} and I love to eat {}!".format(name, food)

    # While within listage...
    for repeater in listage:

        # Extract each dictionary and append them to 'master_list'
        master_list.append(extractor(**repeater)) 


    return master_list

1 Answer

Viraj Deshaval
Viraj Deshaval
4,874 Points

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

def string_factory(values): dict_list = []

for value in values:
    dict_list.append(template.format(**value))
return dict_list