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

Rodrigue Loredon
Rodrigue Loredon
1,338 Points

Help with script strings.py regarding unpacking dictionnaries

The challenge is: 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.

I get the following error message: "Didn't get all the expected output from the 'string_factory' function".

Can someone tell me what's wrong with my code please?

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):

  final_list = []

  for item in dicts:

    newString = string.format(name='name',food='food')

    final_list.append(newString)

  return final_list

2 Answers

Dan Johnson
Dan Johnson
40,533 Points

The list of dictionaries that is being passed in represent keyword arguments for format to use to complete the sentence. The easiest way to extract the values it to unpack them. For example if you had this list of dictionaries:

arguments = [{"arg1": "value1", "arg2": "value2"}, {"arg1": "value3", "arg2": "value4"}]

Then the first statement behaves like the second statement (they will produce equivalent output).

# With unpacking
print( "{arg1} {arg2}".format(**arguments[0]) )
# Without
print( "{arg1} {arg2}".format(arg1="value1", arg2="value2") )
Rodrigue Loredon
Rodrigue Loredon
1,338 Points

Thanks a lot for your help Dan. I was able to pass the challenge with the function written as follows:

def string_factory(dicts,string):

  final_list = []

  for item in dicts:

    newString = string.format(**dicts[dicts.index(item)]

    final_list.append(newString)

  return final_list

It wasn't obvious for me that it was possible to use the ** on a list.

Dan Johnson
Dan Johnson
40,533 Points

For a list you would only use one asterisk to pack or unpack. You use two here since you're getting a dictionary out of the list first, then it's being unpacked.