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

String formatting, unpacking dicts

Can someone help me, i dont know what is going wrong here.

template = "Hi, I'm {} and I love to eat {}!"

def string_factory(args):
    new_list = []
    for item in args:
        new_list.append(template.format(**item))
    return new_list



string_fact = string_factory({'name': 'hasan', 'food': 'kebabs'})
print(string_fact)

2 Answers

Steven Parker
Steven Parker
243,186 Points

The function requires a list of dictionaries as an argument, but you're calling it with a single dictionary as the argument.

But more importantly, the challenge only asks you to create the function. You don't need to call it yourself or print anything.

I already done and completed the challenge at the start of the year. I just came back to revise and test the code on my machine. It gave me this error:

Traceback (most recent call last):
  File "/Users/Hasan/PycharmProjects/beginner_projects/tests.py", line 11, in <module>
    string_fact = string_factory({'name': 'hasan', 'food': 'kebabs'})
  File "/Users/Hasan/PycharmProjects/beginner_projects/tests.py", line 6, in string_factory
    new_list.append(template.format(**item))
TypeError: format() argument after ** must be a mapping, not str
Steven Parker
Steven Parker
243,186 Points

That's right, because by passing it a single dictionary, your loop is iterating through keys (str) from the dictionary instead of dictionaries (mapping) from a list.

But it will work if you call it like this instead:

string_fact = string_factory([{'name': 'hasan', 'food': 'kebabs'}])

It still does not work, now i get this:

Traceback (most recent call last):
  File "/Users/Hasan/PycharmProjects/beginner_projects/tests.py", line 11, in <module>
    string_fact = string_factory([{'name': 'hasan', 'food': 'kebabs'}])
  File "/Users/Hasan/PycharmProjects/beginner_projects/tests.py", line 6, in string_factory
    new_list.append(template.format(**item))
IndexError: tuple index out of range