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 (Retired) Dictionaries String Formatting with Dictionaries

Nicholas Anstis
Nicholas Anstis
2,095 Points

Create a function named string_factory that accepts a list of dictionaries and a string. Return a new list build by usin

As the title says i have to :

Create a function named string_factory that accepts a list of dictionaries and a string. Return a new list build by using .format() on the string, filled in by each of the dictionaries in the list.

My code's down below but hm i can't figure it out :p Hope you can help me

strings.py
dicts = [
    {'name': 'Michelangelo',
     'food': 'PIZZA'},
    {'name': 'Garfield',
     'food': 'lasanga'},
    {'name': 'Walter',
     'food': 'pancakes'},
    {'name': 'Galactus',
     'food': 'worlds'}
]

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

def string_factory(string, string):
  for dicts in string:
    return string.format(**dicts)

2 Answers

Steven Parker
Steven Parker
229,732 Points

Here's a few hints:

  • you can't use the same argument name twice in a function definition (how could you tell them apart later?)
  • you need to build a new list inside the loop (don't return)
  • when you do return after the loop, pass back the newly-created list

If you're still stuck, here's how I did it:


:warning: SPOILER ALERT


def string_factory(dicts, string):
  newlist = []
  for each in dicts:
    newlist.append(string.format(name=each['name'], food=each['food']))
  return newlist

Though I have to say, string_list.append(string.format(**dict)) is a bit more in keeping with the video lesson just prior to the challenge. :+1:

Anjali Pasupathy
Anjali Pasupathy
28,883 Points

That's a much better format for giving out help. I'll have to keep it in mind. Much less "SNAPE KILLS TRINITY WITH ROSEBUD!" than my answer was. (:

Anjali Pasupathy
Anjali Pasupathy
28,883 Points

You're getting there. You formatted the string correctly, though! You can't call both your arguments "string". Also, you're suppose to put all the formatted strings in a list, and then return that list.

def string_factory(dicts, string):
    string_list = []
    for dict in dicts:
        string_list.append(string.format(**dict))
    return string_list

I hope this helps!

Nicholas Anstis
Nicholas Anstis
2,095 Points

Thanks a lot for that fast answer. It helped me a lot.