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 (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
MOD
Chris Freeman
Treehouse Moderator 68,441 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,441 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)

Thanks!