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 (2016, retired 2019) Dictionaries String Formatting with Dictionaries

Adam Welty
Adam Welty
889 Points

Code Challenge String Formatting with Dictionaries

dicts = [ {'name': 'Michelangelo', 'food': 'PIZZA'}, {'name': 'Garfield', 'food': 'lasanga'}, ]

string = "Hi, I'm {name} and I love to eat {food}!"

def string_factory(dicts): string_list = [] for dict in dicts: string_list.append(string.format(**dict)) return string_list

So this was the answer that I used to get through the challenge and admittedly I used help from the forums to complete it. However, could someone take the time to explain what exactly is happening, having a hard time grasping this one. I get everything up until what is actually happening in the 'string_list.append(string.format(**dict))' part.

Thanks for any help.

1 Answer

I would recommend re-watching the video.

Anyway, this:

a = {
  'name': 'Alex',
  'age': 1000,
  'language': 'English',
  'programming_lang': 'Python'
}

fmt = """My name is {name} and I am {age} years old.
I speak {language} and I code in {programming_lang}."""

print(fmt.format(**a))

Is the same thing as this:

fmt = """My name is {name} and I am {age} years old.
I speak {language} and I code in {programming_lang}."""

print(fmt.format(name='Alex',
                 age=1000,
                 language='English',
                 programming_lang='Python'))