I have got KeyError
while using collections.defaultdict
with .format()
method
Shell execution
In [1]: from collections import defaultdict
In [2]: foo = "Foo: {foo}\nBar: {bar}"
In [3]: default = defaultdict(lambda: 0)
In [4]: foo.format(**default)
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-4-799cab129cf2> in <module>
----> 1 foo.format(**default)
KeyError: 'foo'
I am not expecting a KeyError
since I am using a defaultdict
. Why this happening?
Apart from that, I would like to fill the foo
variable with some default values, how can I do that?
Using **
for unpacking converts to a true dict
(or functionally equivalent unrelated data structure; implementation details galore) so the features of defaultdict
don't get used. In this case, you can instead use str.format_map
, which accepts (without unpacking) an arbitrary mapping, without coercing it to a dict
. It exists precisely for this purpose (quoting the docs: "This is useful if for example mapping
is a dict subclass"):
In [5]: foo.format_map(default)
Out[5]: 'Foo: 0\nBar: 0'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With