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 trialNicholas Anstis
2,095 PointsCreate 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
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
231,275 PointsHere'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:
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.
Anjali Pasupathy
28,883 PointsYou'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
2,095 PointsThanks a lot for that fast answer. It helped me a lot.
Anjali Pasupathy
28,883 PointsYou're welcome! (:
Nicholas Anstis
2,095 PointsNicholas Anstis
2,095 PointsThanks a lot too :D
Anjali Pasupathy
28,883 PointsAnjali Pasupathy
28,883 PointsThat'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. (: