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

Peter Otten __peter__ at web.de
Sat Jan 19 09:02:45 CET 2013


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...




More information about the Python-list mailing list