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

David Bouchare
David Bouchare
9,224 Points

[Python] string and dicts code challenge

Hi everyone,

I have another issue with a Python code challenge. When iterating on a list of dictionaries, I cannot seem to find the right way to replace the values in a string and display the correct output. Here is the code I wrote:

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

The problem is that string_list now contains: ['H', 'i', ',', ' ', 'I', "'", 'm', ' ', 'M', 'i', etc...] so it basically adds every single letter to that list and not the sentences.

Any ideas what is wrong in that code?

Thanks in advance again!

2 Answers

Chris Shaw
Chris Shaw
26,676 Points

Hi David,

This is occurring because you're appending each and every letter to the array instead of appending the entire formatted string, instead you want the below.

string_list.append(string.format(**e))

Happy coding =)

David Bouchare
David Bouchare
9,224 Points

Thanks Chris. I changed the code but I still get a "Bummer! Try again" error though... I'll keep looking into it...

Chris Shaw
Chris Shaw
26,676 Points

Hi David,

By the look of it and it's something I missed before is your return statement isn't indented at the same spot the for loop is, I've reformatted it so now it should work without any issues.

def string_factory(dicts, string):
  string_list = []

  for e in dicts:
    string_list.append(string.format(**e))

  return string_list
David Bouchare
David Bouchare
9,224 Points

Thanks, it works fine now!