str.format raises KeyError with dict as parameter

Look at the code below.

s = "{a} {b} {a}"

print(s.format(a=1, b=2))
print(s.format({"a": 1, "b": 2}))

The output is:

1 2 1
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print(s.format({"a": 1, "b": 2}))
KeyError: 'a' 

I thought the str.format(a=1, b=2) is equal with str.format({"a": 1, "b": 2}) but it does not looks so.

First way seems terrible if you have to write a lot of parameters (especially if you have several format strings). I prefer 2nd one.

So can I use dict to format string with duplication of a parameter? Or any short alternative to avoid of long parameter list inside format method brackets?

1 answer

  • answered 2019-09-15 14:58 Jean-François Fabre

    you have to pass the dictionary using named parameter packing or format reverts back to positional to display a string representation of your dictionary (would "work" if s = "{}" for instance, but not what you want).

    s.format(**{"a": 1, "b": 2})
    

    This is easier to comprehend when using a variable:

    d = {"a": 1, "b": 2}
    s.format(d)   # tries to shove "d" into 3-param/named format: wrong
    s.format(**d) # unpacks arguments. Works because keys are compatible with format string