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

Steven D'Aprano steve+comp.lang.python at
Sat Jan 19 05:07:13 CET 2013

I wish to add a key to a dict only if it doesn't already exist, but do it 
in a thread-safe manner.

The naive code is:

if key not in dict:
    dict[key] = value

but of course there is a race condition there: it is possible that 
another thread may have added the same key between the check and the 

How can I add a key in a thread-safe manner?

Any solutions must work with built-in dicts, I cannot use a custom dict 


More information about the Python-list mailing list