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 Packing and Unpacking Dictionaries

Passing unpacked keys/values into a string

>>> my_dict = {'name': 'Kenneth'}
>>> "Hi, my name is {name}!".format(**my_dict)
"Hi, my name is Kenneth!"

Why do we have to pass "name" inside {}?

2 Answers

Chris Freeman
Chris Freeman
Treehouse Moderator 68,029 Points

Good question! Using **my_dict gets translated to the key/value pair name='Kenneth'. When used as an argument to the format method, a named field is expected to match the keyword argument "name".

Is there a particular reason why we need to pass key/value pairs?

It doesn't work if I do this: name = "Tilak" print "My name is {name}".format(name)

I get a key error: Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'name'

Chris Freeman
Chris Freeman
Treehouse Moderator 68,029 Points

As defined in the str.format examples, a key/value pair is only required when the format fields are named.

The error references that the named field "{name}" doesn't have a keyword "name" in the format arguments. If you only wish to use the positional argument name, then use no field name or a numbered field name:

"Hi, my name is {}!".format(name)
"Hi, my name is {0}!".format(name)