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 trialTilak Muruduru Divakar
6,459 PointsPassing 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
Treehouse Moderator 68,441 PointsGood 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
".
Tilak Muruduru Divakar
6,459 PointsThanks!
Tilak Muruduru Divakar
6,459 PointsTilak Muruduru Divakar
6,459 PointsIs 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
Treehouse Moderator 68,441 PointsChris Freeman
Treehouse Moderator 68,441 PointsAs 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: