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

Megan Aki
Megan Aki
3,152 Points

How do I get the function to unpack a list of dictionaries into the same string and return it?

I'm stuck on the code challenge for unpacking a list of dictionaries.

I feel like I need to create some sort of loop that returns the string with the different dictionaries unpacked into it, but I'm completely stumped on how to do this. Help?

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(dicts, string):
  dicts.split() = dicts_li
  for dict in dicts_li:
    return string.format(**dict)

2 Answers

Chris Shaw
Chris Shaw
26,676 Points

Hi Megan,

You're on the right track but have some invalid code.

  1. dicts.split() = dicts_li is invalid and isn't required as we aren't splitting a string
  2. You're returning from within the for loop which is where you should be appending the formatted string into an array

See the below example, I've created a new array called formatted and am appending each formatted order onto it and returning the array once the loop is complete.

def string_factory(orders, format_string):
  formatted = []

  for order in orders:
    formatted.append(format_string.format(**order))

  return formatted

Happy coding!

Megan Aki
Megan Aki
3,152 Points

Thanks for the help!