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

Vito De Tullio vito.detullio at gmail.com
Sat Jan 19 08:25:27 CET 2013


Steven D'Aprano wrote:

> 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
> store.
> 
> How can I add a key in a thread-safe manner?

using locks?

import threading                                                                                                                                                                                                     

lock = threading.Lock()
with lock:
    if key not in dict:
        dict[key] = value


-- 
ZeD




More information about the Python-list mailing list