Bobby Wan-Kenobi
Bobby Wan-Kenobi

Reputation: 915

String format method. Dictionaries

I am learning how to use the string format method, and I've found something I don't understand. When I do:

>>> s = "My {comp[b]}"
>>> s.format(comp = {'a': 'laptop', 'b': 'desktop'})
'My desktop'

I get the expected results. But when I try to define the dictionary out of the method, and just used the name inside:

>>> comp = {'a': 'laptop', 'b': 'desktop'}
>>> s = "My {comp[b]}"
>>> s.format(comp)

I get KeyError: 'comp'. Why?

Upvotes: 0

Views: 49

Answers (2)

Santiago Alessandri
Santiago Alessandri

Reputation: 6855

format differentiates the use between positional and named arguments.

By using the name of the variable inside the format string, you are required to give a named argument with that specific name. In the first you are because you are calling "".format(<name>=<var>) while in the second case your are just giving a positional argument (position 0) that is filled by the comp dictionary.

If you have read the documentation you have noticed that format can use positional arguments in this way: "Hello {0}!".format(<arg0>).

In your second case, instead of giving the required name argument comp you are giving the position argument 0.

Upvotes: 2

Andrew Wilkinson
Andrew Wilkinson

Reputation: 10836

In your second example you're not naming the parameter that you're passing to format. Your final line should be:

>>> s.format(comp=comp)

Upvotes: 5

Related Questions