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

Ben Dooby
Ben Dooby
6,176 Points

Struggling to unpack a list of dictionaries (with two keys 'name' and 'key') into a string.

There is a list of dictionaries each with two keys 'name' and 'food'. A string with two arguments one for 'name' and one for 'food'. I am struggling to format the string.

strings.py
list_of_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(list_of_dicts, string):
    new_list = []
    for dict in list_of_dicts:
        string = string.format(int(**list_of_dicts[dict]))
        new_list.append(string)
    return new_list

1 Answer

Steven Parker
Steven Parker
231,236 Points

:point_right: I see these issues in your code:

  • inside the loop, dict represents an individual dictionary, not an index to one (so you can just: "**dict").
  • you won't want to convert your unpacked dictionary into an int
  • you also won't want to reassign string - use a new local variable instead
Ben Dooby
Ben Dooby
6,176 Points

I see thanks a lot, also why can't I just use the same string I know it doesn't work, but why?

Steven Parker
Steven Parker
231,236 Points

You need the original string so the format can fill in the name and food. If you replace the string with a formatted one, it no longer has the placeholders for the format function to fill in for next time.