Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
218,861 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
218,861 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.