Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Collections (2016, retired 2019) Dictionaries String Formatting with Dictionaries

2,727 Points

Python collections - kwargs.

Hi, i am on this task for few days...

  1. how can i accept a list of dictionaries as an argument?
  2. how to use ** for each dirctory? Thanks, Oren.

Let's test unpacking dictionaries in keyword arguments. 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.

2 Answers

Christopher Shaw
.a{fill-rule:evenodd;}techdegree seal-36
Christopher Shaw
Python Web Development Techdegree Graduate 58,236 Points

The function need to accept a list. We simply give this argument a name, i.e. data

We are asked to return a list, so lets create an empty list we can add too.

We then iterate though the list we were passed, unpack the values and format the template string with the values, lastly append it to our empty list.

def string_factory(data):
    list = []
    for value in data:
        list.append(template.format(name=value['name'], food=value['food']))

    return list

Good answer thank you. This topic is the most difficult to grasp... I still dont get it very well.. after researching online.