Safely add a key to a dict only if it does not already exist?

Mitya Sirenef msirenef at
Sat Jan 19 09:18:42 CET 2013

On 01/19/2013 02:35 AM, Mitya Sirenef wrote:
> On 01/19/2013 02:27 AM, 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 ...
> I guess setdefault with a sentinel default value, then set to your
> new value if d[k] is sentinel?
>  - mitya

Er, that makes no sense.. just setdefault to desired value. -m

Lark's Tongue Guide to Python:

More information about the Python-list mailing list