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

Vito De Tullio vito.detullio at
Sat Jan 19 09:16:48 CET 2013

Peter Otten 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:

yeah, sure, but with a fixed value :)

I mean: if the value is not important, why bother at all trying not to 
override it with an if or a lock or other tecniques? doing

    d['key'] = 'fixed_value'

multiple times in different threads is not a problem in my eyes...


More information about the Python-list mailing list