Path: csiph.com!usenet.pasdenom.info!news.albasani.net!newsfeed.freenet.ag!news2.euro.net!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.001 X-Spam-Evidence: '*H*': 1.00; '*S*': 0.00; '"""': 0.05; 'received:80.91': 0.09; 'received:80.91.229': 0.09; 'received:gmane.org': 0.09; 'received:list': 0.09; 'sure,': 0.09; 'subject:not': 0.11; 'received:80.91.229.3': 0.16; 'received:dip.t-dialin.net': 0.16; 'received:plane.gmane.org': 0.16; 'received:t-dialin.net': 0.16; 'setdefault': 0.16; 'subject:already': 0.16; 'subject:key': 0.16; 'thread-safe': 0.16; 'wrote:': 0.17; 'element': 0.17; '>>>': 0.18; 'suggested': 0.20; 'sets': 0.23; 'header:User-Agent:1': 0.26; 'header:X-Complaints- To:1': 0.28; 'chris': 0.28; "i'm": 0.29; 'sense': 0.31; 'to:addr :python-list': 0.33; 'subject:?': 0.35; 'add': 0.36; 'received:org': 0.36; 'but': 0.36; 'subject:: ': 0.38; 'to:addr:python.org': 0.39; 'header:Received:5': 0.40; 'dict,': 0.84; 'investigated': 0.84; 'subject:add': 0.91 X-Injected-Via-Gmane: http://gmane.org/ To: python-list@python.org From: Peter Otten <__peter__@web.de> Subject: Re: Safely add a key to a dict only if it does not already exist? Date: Sat, 19 Jan 2013 09:02:45 +0100 Organization: None References: <50fa1bf1$0$30003$c3e8da3$5496439d@news.astraweb.com> Mime-Version: 1.0 Content-Type: text/plain; charset="ISO-8859-1" Content-Transfer-Encoding: 7Bit X-Gmane-NNTP-Posting-Host: p5084a632.dip.t-dialin.net User-Agent: KNode/4.7.3 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: 32 NNTP-Posting-Host: 2001:888:2000:d::a6 X-Trace: 1358582581 news.xs4all.nl 6890 [2001:888:2000:d::a6]:51041 X-Complaints-To: abuse@xs4all.nl Xref: csiph.com comp.lang.python:37066 Vito De Tullio wrote: > Chris Rebert wrote: > >>> How can I add a key in a thread-safe manner? >> I'm not entirely sure, but have you investigated dict.setdefault() ? > > but how setdefault makes sense in this context? It's used to set a default > value when you try to retrieve an element from the dict, not when you try > to set a new one ... But it also sets the value if the key is not found: """ setdefault(...) D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """ >>> d = {} >>> d.setdefault(1, 2) 2 >>> d {1: 2} >>> d.setdefault(1, 3) 2 >>> d {1: 2} It has been suggested that get_or_set() would have been a better name for that functionality...