Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

defaultdict raising KeyError when unpacked

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?

like image 832
JPG Avatar asked Dec 18 '22 12:12

JPG


1 Answers

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'
like image 159
ShadowRanger Avatar answered Dec 30 '22 03:12

ShadowRanger