Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!newsfeed.xs4all.nl!newsfeed1.news.xs4all.nl!xs4all!newsgate.cistron.nl!newsgate.news.xs4all.nl!post.news.xs4all.nl!not-for-mail Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.008 X-Spam-Evidence: '*H*': 0.98; '*S*': 0.00; 'key.': 0.09; 'undefined': 0.09; "'xxx'": 0.16; 'accesses': 0.16; 'defaultdict': 0.16; 'dict': 0.16; 'key)': 0.16; 'key?': 0.16; 'lambda': 0.16; 'subclass': 0.16; 'subject:key': 0.16; 'tried:': 0.16; 'wrote:': 0.18; 'basically': 0.19; 'mon,': 0.24; 'define': 0.26; 'header:In- Reply-To:1': 0.27; 'function': 0.29; 'am,': 0.29; 'dec': 0.30; 'message-id:@mail.gmail.com': 0.30; 'work.': 0.31; 'directly,': 0.31; 'keys': 0.31; 'larry': 0.31; 'but': 0.35; 'received:google.com': 0.35; 'there': 0.35; 'i.e.': 0.36; 'subject:skip:d 10': 0.36; 'method': 0.36; 'to:addr:python-list': 0.38; 'to:addr:python.org': 0.39; 'how': 0.40; 'provide': 0.64; 'subject:Setting': 0.96 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20120113; h=mime-version:in-reply-to:references:from:date:message-id:subject:to :content-type; bh=LNggMIUxE1qT5KBj2B0ADohXjkEEdgKWL7xRa/3RCSM=; b=hmnl/wyNjYIy4PlZHdQNv4jIoQ6MYO8Rqa0nesmfsBzcXuQdNAAtzfvIA/R8bdCNyl ba/hquM52D6Gp4FTK/3TTjBoXUlV/8HbGzb6x3GoZtCtsNrL+jC36wdGwzjhzn1etalh rQhPh/wAbyKdCHztGIvXV0BF1jV9Lmt+t/WXsPK3u7XeJ4O0kkAAUuc7i7HlwJcMkao6 bevF2GQ23W3RZqSdN+aTu4oViHBGywYwR726QVz3USmjIo/5jFvyd5DrAvMBHw+N69z+ d9fZC2wKlU5km04r7euc7E/3PgcaCNWk+Nx/pTGNsiMGGNKaotWaVBZbCpLTa+AXVJd/ FdYw== X-Received: by 10.70.102.234 with SMTP id fr10mr102735175pdb.145.1417457555736; Mon, 01 Dec 2014 10:12:35 -0800 (PST) MIME-Version: 1.0 In-Reply-To: References: From: Ian Kelly Date: Mon, 1 Dec 2014 11:11:54 -0700 Subject: Re: Setting default_factory of defaultdict to key To: Python Content-Type: text/plain; charset=UTF-8 X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.15 Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Newsgroups: comp.lang.python Message-ID: Lines: 17 NNTP-Posting-Host: 2001:888:2000:d::a6 X-Trace: 1417457926 news.xs4all.nl 2890 [2001:888:2000:d::a6]:41124 X-Complaints-To: abuse@xs4all.nl Xref: csiph.com comp.lang.python:81762 On Mon, Dec 1, 2014 at 11:05 AM, Larry Martell wrote: > Is there a way to set the default_factory of defaultdict so that > accesses to undefined keys get to set to the key? > > i.e. if d['xxx'] were accessed and there was no key 'xxx' then > d['xxx'] would get set to 'xxx' > > I know I can define a function with lambda for the default_factory, > but I don't see how to access the key. I tried: > > d = defaultdict(lambda: key) > > But that did not work. Not with defaultdict, but you can subclass dict and provide a __missing__ method directly, which is passed the key. This is basically all that defaultdict does.