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

Devin Bartley
Devin Bartley
2,800 Points

String Formatting With Dictionaries - Why is my answer not accepted?

Hello,

I am stuck on the String Formatting With Dictionaries task. The strange thing is that if I run the script, the output comes out correct, but the challenge software seems to think there is an error.

The challenge asks for this:

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.

Here is my script:

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}!"

list = []

newdict = {}

def string_factory(dicts, string):
  for item in dicts:
    newdict = item
    list.append(string.format(**newdict))
  return list

And the error that comes out is this:

<b>isinstant() arg 2 must be a type or a tuple of types!</b>

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

The variable list is not initialized (it is also a function list()). So in your code, your are calling the builtin list.append() function, that needs a list to operate upon. In short you need to add a list = [] above your for loop.

That said, using list as a variable name is not the best as it collides with the builtin function list(). Technically you could also get your code to work by initializing foo = [], then use:

    list.append(foo, string.format(**newdict))
return foo

But that's way off target and not good coding.

In summary, try:

def string_factory(dicts, string):
    mylist = []
    for item in dicts:
        newdict = item
        mylist.append(string.format(**newdict))
    return mylist
Devin Bartley
Devin Bartley
2,800 Points

Thank you so much, Chris. This is very helpful!

I now understand why it wasn't working.

Have a great day!