Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #82049

Re: Setting default_factory of defaultdict to key

Date 2014-12-05 15:51 -0500
From John J Posner <johnjposner@verizon.net>
Subject Re: Setting default_factory of defaultdict to key
Newsgroups comp.lang.python
Message-ID <mailman.16662.1417949320.18130.python-list@python.org> (permalink)

Show all headers | View raw


At the beginning of this thread, Ian Kelly said:

     Not with defaultdict, but you can subclass dict and provide a
     __missing__ method directly

To emphasize, you don't need to subclass "defaultdict" -- you need only subclass "dict" itself:

class MyDict(dict):
     def __missing__(self, key):
         self[key] = key
         return key

md = MyDict()
md[1] = 111
_ = md[2]
_ = md["another key"]


## md now looks like this:  {1: 111, 2: 2, 'another key': 'another key'}

The defaultdict documentation is confusing on this point. A *long* time ago, I filed Bug 9536 to improve the doc, but the fix hasn't bubbled to the surface yet.

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Setting default_factory of defaultdict to key John J Posner <johnjposner@verizon.net> - 2014-12-05 15:51 -0500

csiph-web